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
作为响应。
请帮助