Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate reference field in virtual method in Mongoose?

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?

like image 381
Burak Avatar asked Dec 19 '12 10:12

Burak


People also ask

What is virtual populate in Mongoose?

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.

How does populate work in Mongoose?

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.

What does REF do in Mongoose?

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.

What is virtual method in Mongoose?

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.


2 Answers

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)
})
like image 79
matthewtole Avatar answered Nov 01 '22 08:11

matthewtole


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
like image 44
Elankeeran Avatar answered Nov 01 '22 09:11

Elankeeran