egg.js 一个model中如何导出多个schma,并在service中读取?
发布于 8 个月前 作者 fengyun2 747 次浏览 来自 问答

定义这样一个 model

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const foodSchema = new Schema({
    restaurant_id: { type: Number, isRequired: true },
    category_id: { type: Number, isRequired: true },
    description: { type: String, default: '' },
    image_path: String,
    name: { type: String, isRequired: true },
  });

  foodSchema.index({ item_id: 1 });

  const menuSchema = new Schema({
    description: String,
    is_selected: { type: Boolean, default: true },
    icon_url: { type: String, default: '' },
    name: { type: String, isRequired: true },
    id: { type: Number, isRequired: true },
    restaurant_id: { type: Number, isRequired: true },
    type: { type: Number, default: 1 },
    foods: [ foodSchema ],
  });

  menuSchema.index({ id: 1 });

  const Food = mongoose.model('Food', foodSchema);
  const Menu = mongoose.model('Menu', menuSchema);
  return { Food, Menu };
};

service中 如何读取这个 model 呢?

async getFoods(id) {
    const { ctx } = this;
    console.log(ctx.model.Food); // 这里打印处理没有food的实例
}
3 回复

一个model对应一个表

@nodeper 但是menu里面包含了foods,就没有办法么?

一个model对应一个表; 使用ref关联;

//./model/food.js
var foodSchema = Schema({
  ...
});
return mongoose.model('Food', foodSchema);

//./model/menu.js
var menuSchema = Schema({
  ...
  foods: [{ type: Schema.Types.ObjectId, ref: 'Food' }]
});
return mongoose.model('Menu', menuSchema);

查询使用populate; https://mongoosejs.com/docs/populate.html

回到顶部