what does ref means mongooose
ref
basically means that mongoose
would store the ObjectId
values and when you call populate
using those ObjectIds would fetch and fill the documents for you. So in this case:
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
An ObjectId
for the Story would be only stored in the Person stories
array and when you call on populate('stories')
mongoose would go and do another query to find and match all the ObjectId
and return you the actual Stories
objects.
So ref
just tells mongoose that you want to store there a reference to another model and at some point you want to populate
those and get the full blown model by that reference.
In a sense it is nothing more than a foreign
key to another collection by which you fetch the actual document when populate
is called.
Here is the code broken down:
Story.findOne({ title: 'Casino Royale' }) // <-- filter on title // once a story is found populate its `author` with full author document // instead of the `ObjectId` stored by the `ref` .populate('author') // execute the current pipeline .exec(function (err, story) { // handle the resulting record if (err) return handleError(err); console.log('The author is %s', story.author.name); });
Hope this helps.