使用在猫鼬中具有嵌套模式的Model填充嵌套模式

时间:2020-10-18 12:24:30

标签: javascript node.js mongodb mongoose mongoose-schema

categorySchema嵌套在userSchema中的用户模型:

const categorySchema = new mongoose.Schema({
  categoryName: {
    type: String,
    maxlength: [40, 'Expense name must not be more than 40 characters'],
  },
  categoryValue: {
    type: String,
  },
)

const userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    trim: true,
    required: [true, 'Full Name is required'],
  },
categoriesData: {
    type: [categorySchema],
},
);

const User = mongoose.model('User', userSchema);

预算模型,其中收入模式嵌套在budgetSchema中,

const revenueSchema = new mongoose.Schema({
  categoryData: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
  }
)

const budgetSchema = new mongoose.Schema({
   revenueData: { type: [revenueSchema] }
})

//My Code for populate
budgetSchema.pre(/^find/, function (next) {
  this.populate({
    path: 'revenueData',
    populate: [
      {
        path: 'categoryData',
        select: '-__v -_id',
      },
    ],
  });

  next();
});

const Budget = mongoose.model('Budget', budgetSchema);

revenueSchema中,categoryData属性包含在categorySchema中创建的文档的对象ID,该对象的ID嵌套在用户模型中。 因此,只要在预算模型中有一个“查找”查询,我就想用来自用户模型categoryData中相应的id文档填充预算模型中的categorySchema。 我已经尝试过,但是在类别数据中得到了null作为响应。

请帮助

0 个答案:

没有答案