MongoDB does not join, but sometimes we need to refer to other collection documents, this time we need to populate.
We can populate a single document, multiple document, plain object, multiple plain objects, or all object returned by query.
var mongoose = require (' Mongoose '); var Schema = Mongoose. Schema;var Personschema = new Schema ({ _id:number, name:string, age:number, stories: [{type: Schema.Types.ObjectId, ref: ' Story '}]}), var storyschema = new Schema ({ _creator: {type:number, ref: ' Person '}, Title:string, fans: [{type:number, ref: ' Person '}]}); var story = Mongoose.model ("story", Storyschema); var person = m Ongoose.model (' person ', personschema);
So far we've created two of the model. The person model has a stories field that is a collection of Objectid. Ref is telling Mongoose which model should be popluate.
Story has a _creator field that is number type. He's the ID of Personschema.
Saving ref
Save a ref
var arron = new Person ({_id:0, Name: ' Aaron ', age:100}), Arron.save (function (err) { if (err) return HandleError (ERR); C1/>var story1 = new Story ({ titile: ' Once upon a Timex ', _creator:arron._id //Assigned person's _id }); Story1.save (function (err) { if (err) return HandleError (ERR); });});
Populate
The _creator that fills the story
Story . FindOne ({title: ' Once upon a Timex ') . Populate (' _creator ') . EXEC (Fucntion (err, story) { if (err) return HandleError (err); Console.log (Story._creator.name)//Aaron });
Field selection
If we don't want to fill the story with the whole _creator, we just want to populate _creator's name.
Story.findone ({title:/timex/i}). Populate (' _creator ', ' name ')//Only return the Persons name.exec (function (err, story) { if (err) return HandleError (err); Console.log (' The creator is%s ', story._creator.name); Prints "The creator is Aaron" console.log (' The Creators age is%s ', story._creator.age); Prints "The creators is Null"})
Fill multiple paths at once
If we want to fill more than one path at a time, what's wrong?
Story.find (...). Populate (' Fans author ')//Space delimited path names.exec ()
Another way of writing
Story.find (...). Populate (' fans '). Populate (' author '). EXEC ()
Fill by condition
Story.find (...). Populate ({ path: ' Fans ', match: {age: {$gte: +}}, select: ' Name-_id ', options: {Limit:5}}). EXEC ()
Mongoose Guide-Population