Mongoose:用投影填充对象的嵌套数组

var CarSchema = new Schema({ name: {type: String}, partIds: [{type: Schema.Types.ObjectId, ref: 'Part'}], }); var PartSchema = new Schema({ name: {type: String}, props: [ { colour: {type: String}, shape: {type:String} } ], }); 

例如

 Car = { name: "BMW", partIds:[ObjectId("57baa43e152654f80aac36a6")]} Part = { _id: ObjectId("57baa43e152654f80aac36a6"), name: "Piston", props: [{colour:"red", shape: "Cubical"},{colour:"green", shape: "cylindrical"}] 

所以,当我查询我应该得到这样的文档:

 Car = { name: "BMW", partIds: [{ _id:ObjectId("57baa43e152654f80aac36a6"), name:"Piston", props: [{colour:"red", shape:"cubical"}] } 

道具数组只能有红色的元素

我想用部件数组填充Car,使其prop数组只有红色的对象。 有没有办法做到这一点,或者我将不得不采取老式的方式,并通过道具arrays匹配其颜色与红色循环。

您可以通过在您的populate调用中提供select选项来执行此操作:

 Car.findOne() .populate({ path: 'partIds', select: { props: { $elemMatch: { colour: 'red' } }, name: 1 } }) .exec(callback); 

结果:

 { _id: 57c085451cd8dfcdf814f640, name: 'BMW', partIds: [ { _id: 57baa43e152654f80aac36a6, name: 'Piston', props: [ { colour: 'red', shape: 'Cubical' } ] } ] } 

select使用$elemMatch投影算子来select红色的props元素。

你可以尝试这个,它应该得到你想要的。

 car.find({"partIds.props.colour" : "red"}) .populate('partIds') .exec(function(err,result){...});