Population

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, plain object, multiple plain objects, or all objects returned from a query. Let’s look at some examples.

  1. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. var personSchema = Schema({
  4. _id: Schema.Types.ObjectId,
  5. name: String,
  6. age: Number,
  7. stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
  8. });
  9. var storySchema = Schema({
  10. author: { type: Schema.Types.ObjectId, ref: 'Person' },
  11. title: String,
  12. fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
  13. });
  14. var Story = mongoose.model('Story', storySchema);
  15. var Person = mongoose.model('Person', personSchema);

So far we’ve created two Models. Our Person model has its stories field set to an array of ObjectIds. The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model.

Note: ObjectId, Number, String, and Buffer are valid for use as refs. However, you should use ObjectId unless you are an advanced user and have a good reason for doing so.

Saving refs

Saving refs to other documents works the same way you normally save properties, just assign the _id value:

  1. var author = new Person({
  2. _id: new mongoose.Types.ObjectId(),
  3. name: 'Ian Fleming',
  4. age: 50
  5. });
  6. author.save(function (err) {
  7. if (err) return handleError(err);
  8. var story1 = new Story({
  9. title: 'Casino Royale',
  10. author: author._id // assign the _id from the person
  11. });
  12. story1.save(function (err) {
  13. if (err) return handleError(err);
  14. // thats it!
  15. });
  16. });

Population

So far we haven’t done anything much different. We’ve merely created a Person and a Story. Now let’s take a look at populating our story’s author using the query builder:

  1. Story.
  2. findOne({ title: 'Casino Royale' }).
  3. populate('author').
  4. exec(function (err, story) {
  5. if (err) return handleError(err);
  6. console.log('The author is %s', story.author.name);
  7. // prints "The author is Ian Fleming"
  8. });

Populated paths are no longer set to their original _id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.

Arrays of refs work the same way. Just call the populate method on the query and an array of documents will be returned in place of the original _ids.

Note: mongoose >= 3.6 exposes the original _ids used during population through the document#populated() method.

Setting Populated Fields

In Mongoose >= 4.0, you can manually populate a field as well.

  1. Story.findOne({ title: 'Casino Royale' }, function(error, story) {
  2. if (error) {
  3. return handleError(error);
  4. }
  5. story.author = author;
  6. console.log(story.author.name); // prints "Ian Fleming"
  7. });

Note that this only works for single refs. You currently can’t manually populate an array of refs.

Field selection

What if we only want a few specific fields returned for the populated documents? This can be accomplished by passing the usual field name syntax as the second argument to the populate method:

  1. Story.
  2. findOne({ title: /casino royale/i }).
  3. populate('author', 'name'). // only return the Persons name
  4. exec(function (err, story) {
  5. if (err) return handleError(err);
  6. console.log('The author is %s', story.author.name);
  7. // prints "The author is Ian Fleming"
  8. console.log('The authors age is %s', story.author.age);
  9. // prints "The authors age is null'
  10. })

Populating multiple paths

What if we wanted to populate multiple paths at the same time?

  1. Story.
  2. find(...).
  3. populate('fans').
  4. populate('author').
  5. exec()

If you call populate() multiple times with the same path, only the last one will take effect.

  1. // The 2nd `populate()` call below overwrites the first because they
  2. // both populate 'fans'.
  3. Story.
  4. find().
  5. populate({ path: 'fans', select: 'name' }).
  6. populate({ path: 'fans', select: 'email' });
  7. // The above is equivalent to:
  8. Story.find().populate({ path: 'fans', select: 'email' });

Query conditions and other options

What if we wanted to populate our fans array based on their age, select just their names, and return at most, any 5 of them?

  1. Story.
  2. find(...).
  3. populate({
  4. path: 'fans',
  5. match: { age: { $gte: 21 }},
  6. // Explicitly exclude `_id`, see http://bit.ly/2aEfTdB
  7. select: 'name -_id',
  8. options: { limit: 5 }
  9. }).
  10. exec()

Refs to children

We may find however, if we use the author object, we are unable to get a list of the stories. This is because no story objects were ever ‘pushed’ onto author.stories.

There are two perspectives here. First, you may want the author know which stories are theirs. Usually, your schema should resolve one-to-many relationships by having a parent pointer in the ‘many’ side. But, if you have a good reason to want an array of child pointers, you can push() documents onto the array as shown below.

  1. author.stories.push(story1);
  2. author.save(callback);

This allows us to perform a find and populate combo:

  1. Person.
  2. findOne({ name: 'Ian Fleming' }).
  3. populate('stories'). // only works if we pushed refs to children
  4. exec(function (err, person) {
  5. if (err) return handleError(err);
  6. console.log(person);
  7. });

It is debatable that we really want two sets of pointers as they may get out of sync. Instead we could skip populating and directly find() the stories we are interested in.

  1. Story.
  2. find({ author: author._id }).
  3. exec(function (err, stories) {
  4. if (err) return handleError(err);
  5. console.log('The stories are an array: ', stories);
  6. });

The documents returned from query population become fully functional, removeable, saveable documents unless the lean option is specified. Do not confuse them with sub docs. Take caution when calling its remove method because you’ll be removing it from the database, not just the array.

Populating an existing document

If we have an existing mongoose document and want to populate some of its paths, mongoose >= 3.6 supports the document#populate() method.

Populating multiple existing documents

If we have one or many mongoose documents or even plain objects (like mapReduce output), we may populate them using the Model.populate() method available in mongoose >= 3.6. This is what document#populate() and query#populate() use to populate documents.

Populating across multiple levels

Say you have a user schema which keeps track of the user’s friends.

  1. var userSchema = new Schema({
  2. name: String,
  3. friends: [{ type: ObjectId, ref: 'User' }]
  4. });

Populate lets you get a list of a user’s friends, but what if you also wanted a user’s friends of friends? Specify the populate option to tell mongoose to populate the friends array of all the user’s friends:

  1. User.
  2. findOne({ name: 'Val' }).
  3. populate({
  4. path: 'friends',
  5. // Get friends of friends - populate the 'friends' array for every friend
  6. populate: { path: 'friends' }
  7. });

Populating across Databases

Let’s say you have a schema representing events, and a schema representing conversations. Each event has a corresponding conversation thread.

  1. var eventSchema = new Schema({
  2. name: String,
  3. // The id of the corresponding conversation
  4. // Notice there's no ref here!
  5. conversation: ObjectId
  6. });
  7. var conversationSchema = new Schema({
  8. numMessages: Number
  9. });

Also, suppose that events and conversations are stored in separate MongoDB instances.

  1. var db1 = mongoose.createConnection('localhost:27000/db1');
  2. var db2 = mongoose.createConnection('localhost:27001/db2');
  3. var Event = db1.model('Event', eventSchema);
  4. var Conversation = db2.model('Conversation', conversationSchema);

In this situation, you will not be able to populate() normally. The conversation field will always be null, because populate() doesn’t know which model to use. However, you can specify the model explicitly.

  1. Event.
  2. find().
  3. populate({ path: 'conversation', model: Conversation }).
  4. exec(function(error, docs) { /* ... */ });

This is known as a “cross-database populate,” because it enables you to populate across MongoDB databases and even across MongoDB instances.

Dynamic References

Mongoose can also populate from multiple collections at the same time. Let’s say you have a user schema that has an array of “connections” - a user can be connected to either other users or an organization.

  1. var userSchema = new Schema({
  2. name: String,
  3. connections: [{
  4. kind: String,
  5. item: { type: ObjectId, refPath: 'connections.kind' }
  6. }]
  7. });
  8. var organizationSchema = new Schema({ name: String, kind: String });
  9. var User = mongoose.model('User', userSchema);
  10. var Organization = mongoose.model('Organization', organizationSchema);

The refPath property above means that mongoose will look at the connections.kind path to determine which model to use for populate(). In other words, the refPath property enables you to make the ref property dynamic.

  1. // Say we have one organization:
  2. // `{ _id: ObjectId('000000000000000000000001'), name: "Guns N' Roses", kind: 'Band' }`
  3. // And two users:
  4. // {
  5. // _id: ObjectId('000000000000000000000002')
  6. // name: 'Axl Rose',
  7. // connections: [
  8. // { kind: 'User', item: ObjectId('000000000000000000000003') },
  9. // { kind: 'Organization', item: ObjectId('000000000000000000000001') }
  10. // ]
  11. // },
  12. // {
  13. // _id: ObjectId('000000000000000000000003')
  14. // name: 'Slash',
  15. // connections: []
  16. // }
  17. User.
  18. findOne({ name: 'Axl Rose' }).
  19. populate('connections.item').
  20. exec(function(error, doc) {
  21. // doc.connections[0].item is a User doc
  22. // doc.connections[1].item is an Organization doc
  23. });

Populate Virtuals

New in 4.5.0

So far you’ve only populated based on the _id field. However, that’s sometimes not the right choice. In particular, arrays that grow without bound are a MongoDB anti-pattern. Using mongoose virtuals, you can define more sophisticated relationships between documents.

  1. var PersonSchema = new Schema({
  2. name: String,
  3. band: String
  4. });
  5. var BandSchema = new Schema({
  6. name: String
  7. });
  8. BandSchema.virtual('members', {
  9. ref: 'Person', // The model to use
  10. localField: 'name', // Find people where `localField`
  11. foreignField: 'band', // is equal to `foreignField`
  12. // If `justOne` is true, 'members' will be a single doc as opposed to
  13. // an array. `justOne` is false by default.
  14. justOne: false
  15. });
  16. var Person = mongoose.model('Person', PersonSchema);
  17. var Band = mongoose.model('Band', BandSchema);
  18. /**
  19. * Suppose you have 2 bands: "Guns N' Roses" and "Motley Crue"
  20. * And 4 people: "Axl Rose" and "Slash" with "Guns N' Roses", and
  21. * "Vince Neil" and "Nikki Sixx" with "Motley Crue"
  22. */
  23. Band.find({}).populate('members').exec(function(error, bands) {
  24. /* `bands.members` is now an array of instances of `Person` */
  25. });

Keep in mind that virtuals are not included in toJSON() output by default. If you want populate virtuals to show up when using functions that rely on JSON.stringify(), like Express’ res.json() function, set the virtuals: true option on your schema’s toJSON options.

  1. // Set `virtuals: true` so `res.json()` works
  2. var BandSchema = new Schema({
  3. name: String
  4. }, { toJSON: { virtuals: true } });

If you’re using populate projections, make sure foreignField is included in the projection.

  1. Band.
  2. find({}).
  3. populate({ path: 'members', select: 'name' }).
  4. exec(function(error, bands) {
  5. // Won't work, foreign field `band` is not selected in the projection
  6. });
  7. Band.
  8. find({}).
  9. populate({ path: 'members', select: 'name band' }).
  10. exec(function(error, bands) {
  11. // Works, foreign field `band` is selected
  12. });

Next Up

Now that we’ve covered query population, let’s take a look at connections.