我遇到了以下情况,我需要更好地了解人口是如何工作的:我有3个模式如下。我需要过滤子模式的基础上祖父属性名称。我创建了一个填充前发现,但看起来像填充没有帮助过滤的基础上属性,而只有对象ID。控制器代码如下所示:
filter= {childname: req.params.childname, 'child.parent.grandparent.grandparentname': req.params.grandparent};
const result = await Child.find(filter)
const childSchema = new mongoose.Schema(
{
childname: {
type: String,
},
parent:{
type:mongoose.Schema.ObjectId,
ref: 'Parent',
required: [true, "Parent missing"],
// select: false
}
},
{ timestamps: true },
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
childSchema.pre(/^find/, function(next) {
this.populate
(
{path: 'parent',select: '-__v',
populate: [
{ path: 'grandparent', select: 'grandparentname' }
]
});
next();
});
const Child = mongoose.model( 'Child', childSchema);
module.exports = Child;
const parentSchema = new mongoose.Schema(
{
parentname: {
type: String,
},
grandparent:{
type:mongoose.Schema.ObjectId,
ref: 'grandparent',
required: [true, "Grand parent missing"],
// select: false
},
},
{ timestamps: true },
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
const Parent = mongoose.model( 'Parent', parentSchema);
module.exports = Parent;
const grandparentSchema = new mongoose.Schema(
{
grandparentname: {
type: String,
}
},
{ timestamps: true },
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
const Grandparent = mongoose.model( 'Grandparent', grandparentSchema);
module.exports = Grandparent;
1条答案
按热度按时间vsdwdz231#
我有答案了!
首先-删除您的
Childschema.pre('^/find...
并使用下一个代码:
我试着用populate来做,但是没有结果:(所以,我用aggregate找到了解决方案,它起作用了!)