2016-05-03 32 views
2

這裏是我的代碼來獲得一個平面佈置圖和填充這個填充上的貓鼬條件的基礎上,MongoDB的

鏈接的所有單位請參見下面的代碼:

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); 
}); 

但我想只有那些填充flats where 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 }, 

}); 
+0

爲'Floorplan'和'Flat'模型顯示模式定義會很有幫助,'Flat'模型是否也有'isDeleted'屬性? – chridam

+0

完成! @chridam –

回答

5

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); 
});