Here is my code to get one floorplan and populate all flats linked with this
see the code below :
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); });
But I want to populate only those flats where isDeleted : false How to achive this ??
Schema of floorplan
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 } });
Schema of flat
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 }, });
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
populate() function in mongoose is used for populating the data inside the reference. In your example StorySchema is having _creator field which will reference to the _id field which is basically the ObjectId of the mongodb document. populate() function can accept a string or an object as an input.
Types. ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
The populate()
method has an option which allows for filtering, you can either try this
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); });
or
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With