【问题标题】:Populate on basis of condition in mongoose, mongoDB根据 mongoose、mongoDB 中的条件填充
【发布时间】:2016-05-03 19:43:57
【问题描述】:

这是我的代码,用于获取一个平面图并填充与此相关的所有公寓

请看下面的代码:

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 },

});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 2019-06-25
      • 2020-09-06
      • 2021-06-04
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多