CNode

egg.js如何在不使用egg-mongoose情况下写model层

问答
Llaoqiren发布于8 年前最后回复8 年前2 回复5403 浏览0 收藏

发现现有的例子都是像这样:

// {app_root}/app/model/user.js
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const conn = app.mongooseDB.get('db1'); 

  const UserSchema = new Schema({
    userName: { type: String  },
    password: { type: String  },
  });

  return conn.model('User', UserSchema);
}

当我不使用egg-mongoose时,直接用egg-mongo时,我想在model层封装一些数据库操作方法:

// model/topic.js
module.exports = app => {
    const mongo = app.mongo;

    return {
        async queryAllTopics(){
            try {
                let result = await mongo.topic.find();
            } catch(err){
                console.error(err);
            }
        },
        async addTopic(topic){
            try {
                let result = await mongo.topic.insert(topic);
            } catch(err){
                console.error(err);
            }
        }
    }
};

然后我在service里去取

let result = await this.ctx.model.topic.addTopic(topic); return result;

发现是取不到这个this.ctx.model.topic的,请问这种应该怎么处理呢?

查看回复

回复 (2)

L
liuzhiguo11#1·8 年前

需要自己实现,app.loadToContext({...})了解一下

L
laoqiren#2·8 年前
参与回复
登录后即可参与回复。登录