I have following schema.
var ItemSchema = new Schema({
name : String
,location: {
address: { type: String, default:''},
geolocation: {longitude: Number, latitude:Number},
place : {type: Schema.Types.ObjectId, ref:'Place'}
},
ranking_in_place : Number })
Place is a reference to Place schema which has name, city, country etc. fields.
I want to create a virtual for ranking_summary:
ItemSchema.virtual('ranking_summary').get(function() {
if(this.ranking_in_place <= 5){
if(this.ranking_in_place == 1){
return "Most popular item" + " in " + this.location.place.name
}
}
})
I cannot get this.location.place.name value because this.location.place is a reference, and not populated. How can I access this value?
Populate. Mongoose also supports populating virtuals. A populated virtual contains documents from another collection. To define a populated virtual, you need to specify: The ref option, which tells Mongoose which model to populate documents from.
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
Mongoose virtuals are document properties that you can get and set but are not saved in MongoDB. These properties are computed whenever you access them. Virtual properties are useful for formatting and combining fields, and de-composing a single value into multiple values before storing in the collection.
Have you made sure to call .populate() on your queries? Otherwise, Mongoose won't know to pull in the reference object. Example:
ItemModel.findOne().populate('place').exec(function (err, item) {
console.log(item.ranking_in_place)
})
Model.find().populate(path, fields, conditions, options);
so for options you could use
{ sort: 'order' } // ascending
{ sort: [['order', 1 ]] } // ascending
{ sort: [['order', 'asc' ]] } // ascending
{ sort: [['order', 'desc' ]] } // ascending
{ sort: [['order', -1 ]] } // descending
{ sort: [['order', 'desc' ]] } // descending
{ sort: [['order', 'descending' ]] } // descending
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With