MongoDB Populate Nested Subdocument

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, a plain object, multiple plain objects, or all objects returned from a query.

var modelA = new Schema({
	firstName: {
		type: String,
		trim: true,
	},
	refModelB: {
	  type: Schema.ObjectId,
	  ref: ModelB
	},
});


var modelB = new Schema({
	name: {
		type: String,
		trim: true,
	},
	refModelC: {
	  type: Schema.ObjectId,
	  ref: ModelC
	},
});

var modelC = new Schema({
	name: {
		type: String,
		trim: true,
	},
});
modelA
    .find()
    .populate({path: 'modelB', populate: {path: 'refModelC'}})
    .exec(function (err, docs) {
        done(err, doc);
    });

#mongoose #mongodb

MongoDB Populate Nested Subdocument
4.65 GEEK