在egg.js中使用mongodb


1.egg.js官網只推薦了mysqle,要用mongodb得另找資料。通過查找,大家都在用Mongoose連接,於是乎學習

網站鏈接:https://www.npmjs.com/package/egg-mongoose

2.第一步:安裝

npm i egg-mongoose --save  

3.配置

安裝完成之后在目錄/config/plugin.js中引用

exports.mongoose = {
  enable: true,
  package: 'egg-mongoose',
};

 

在/config/config.default.js中加入

// 數據庫配置
  exports.mongoose = {
    client: {
      url: 'mongodb://127.0.0.1:27017/egg_article', // 你的數據庫地址,egg_article是你數據庫得名字
      options: {
        useNewUrlParser: true,
      },
    },
  };

4.簡單得列子

在app下新建文件夾model,model下新建article.js文件,完整路徑app/model/article.js

article.js內容

'use strict';

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  // 下面得操作是連接數據庫
  const ArticleSchema = new Schema({
    // 修改和新增用到,規定字段得類型和其他條件等
    title: {
      type: String,
      required: true,
    },
    _id: {
      type: Schema.ObjectId,
      ref: 'Tags',
      required: true,
    },
    summary: {
      type: String,
    },
  }, { versionKey: false });

  return mongoose.model('Article', ArticleSchema, 'article'); // 我的理解:Article是指定查找的入口,隨便取;ArticleSchema是參數;article是你數據集合表的名稱
};

app/service/article.js

'use strict';

const Service = require('egg').Service;

class ArticleService extends Service {
  /**
	 * 根據ID獲取單個項目
	 */
  async getProjectById() {
    const { ctx, app } = this;
    try {
      const results = await ctx.model.Article.find({ // Article為modal/article.js里面命名的名字
        _id: app.mongoose.Types.ObjectId('5da034149b6e823ca2ea809d'),
      });
      return results;
    } catch (err) {
      ctx.body = JSON.stringify(err);
    }
  }
}
module.exports = ArticleService;

app/controller/article.js

'use strict';
const Controller = require('egg').Controller;

class ArticleController extends Controller {
  async index() {
    const { ctx } = this;
    const res = await ctx.service.article.getProjectById();
    ctx.body = res; // 返回值顯示
  }
}
module.exports = ArticleController;

router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/article', controller.article.index);
};

訪問地址欄要改到/article

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM