I came across the following line of code which I couldn't understand ,although there are lot of tutorials that gives information related to examples of populate
but there is none that explains what exactly it means.Here is a example
var mongoose = require('mongoose'), Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String,
age : Number,
stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : {
type: Schema.ObjectId,
ref: 'Person'
},
title : String,
fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Story.findOne({ title: /Nintendo/i }).populate('_creator') .exec(function (err, story) {
if (err) ..
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})
populate()
function is mongoose is used for populating the data inside the reference. In your exampleStorySchema
is having_creator
field which will reference to the_id
field which is basically theObjectId
by of the mongodb document.Where string is the field name which is required to be populated. In your case that is
_creator
. After mongoose found one doc from mongodb and the result of that is like belowYou can find the documents of
populate()
function of mongoose below. http://mongoosejs.com/docs/2.7.x/docs/populate.htmlI came across that question randomly, but I feel I need to help here, even if it's old because I'm not convinced by the way it is explained :
That might be very clear for natives English speaker, but maybe not for others.
TL;DR
Populate will automatically replace the specified path in the document, with document(s) from other collection(s)
Long version
Let's take your example
Will return a Story of that kind :
In some case, those kind of request would be enough, because we don't care about the author or the fans so, having some ID won't bother us much.
But in the case where i need that author, i'll need to make another request to find it in database. Except, that here in mongoose we have a clever function called populate() that we can chained to our previous request in order to directly get that information in our answer without explictly doing an additional request.
will return
But maybe, that's too much information, and we don't want the stories that he wrote and his age and name are enough. Populate can then take an other argument containing the field that we need
result ==>