根据mongoose,mongoDB中的条件填充

时间:2016-05-03 11:26:10

标签: node.js mongodb mongoose

这是我的代码,以获得一个平面图并填充与此

链接的所有单位

请参阅以下代码:

var floorplan = Floorplan.find({ 
    project: req.params.project, 
    tower: req.params.tower, 
    isDeleted: false 
});
floorplan.populate('flats').exec(function(err, floorplan) {
    if (err) { return res.send(err); }
    if (!floorplan) { return res.status(401).json(); }
    res.status(200).json(floorplan);
});

但我想只填充isDeleted:false的那些单位 如何实现这个?

平面图的架构

var FloorplanSchema = new Schema({
    project: { type: Schema.ObjectId, ref: "Project" },
    flats: [{ type: Schema.ObjectId, ref: "Flat" }],
    tower: [{ type: Schema.ObjectId, ref: "Tower" }],
    unitType: String,
    area: Number,
    floorPlan2D: String,
    floorPlan3D: String,
    livingRoomArea: Number,
    kitchenArea: Number,
    balconies: Number,
    bathRooms: Number,
    isDeleted: { type: Boolean, 'default': false },
    createdAt: { type: Date, 'default': Date.now }
});

平面图式

var FlatSchema = new Schema({
    tower: { type: Schema.ObjectId, ref: "Tower" },
    floorplan: { type: Schema.ObjectId, ref: "Floorplan" },
    project: { type: Schema.ObjectId, ref: "Project" },
    status: String,
    floor: Number,
    size: String,

    superbuiltup_area: Number,

    directionFacing: String,
    furnishingState: String,
    flooringType: String,
    createdAt: { type: Date, 'default': Date.now },
    isDeleted: { type: Boolean, 'default': false },

});

1 个答案:

答案 0 :(得分:14)

populate() 方法有一个允许过滤的选项,你可以尝试这个

Floorplan
.find({ 
    project: req.params.project, 
    tower: req.params.tower, 
    isDeleted: false 
})
.populate({
    path: 'flats',
    match: { isDeleted: false }
})
.exec(function(err, floorplan) {
    if (err) { return res.send(err); }
    if (!floorplan) { return res.status(401).json(); }
    res.status(200).json(floorplan);
});

Floorplan
.find({ 
    project: req.params.project, 
    tower: req.params.tower, 
    isDeleted: false 
})
.populate('flats', null, { isDeleted: false })
.exec(function(err, floorplan) {
    if (err) { return res.send(err); }
    if (!floorplan) { return res.status(401).json(); }
    res.status(200).json(floorplan);
});