Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I came across the following line of code which I couldn't understand, although there are lot of tutorials that give 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" 

})

2 Answers

0 votes
by (106k points)

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 below

_creator: { 

name: "SomeName", 

age: SomeNumber, 

stories: [Set Of ObjectIDs of documents in stories collection in mongodb] 

}, 

title: "SomeTitle", 

fans: [Set of ObjectIDs of documents in persons collection in mongodb]

Populate can also accept the object as an input.

0 votes
by (50.2k points)

MongoDB has the join-like $lookup aggregation stage operator in versions greater and equal to 3.2. Mongoose has a further powerful alternative called populate(), which lets you reference documents in other collections.

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

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...