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

Mongoose: Populating object's nested array with projection

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"}]
     }

道具数组应该只有红色元素

我想用 Part Array 填充 Car,使其 prop 数组只有红色的对象。无论如何都可以这样做,还是我必须采用老式的方式并循环遍历将其颜色与红色匹配的道具数组。

你可以试试这个,它应该能满足你的需要。

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

您可以通过在 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 元素。