Populating Mongoose objects from id to new field Populating Mongoose objects from id to new field mongoose mongoose

Populating Mongoose objects from id to new field


There's a way to do this - it's called Virtuals (see docs).The idea is to create a "virtual property" which is not actually saved to the DB and acts as a computed property. As per the example provided by qinshenxue on the related github issue:

// declare your ID field as a regular stringvar countrySchema = new mongoose.Schema({    capitalId: {type:String}});// create a virtual field which links between the field you've just declared // and the related collection. // localField is the name of the connecting field, // foreign field is a corresponding field in the connected collection// justOne says that it'll populate a single connected object, // set it to false if you need to get an arraycountrySchema.virtual('capital',{    ref: 'City',    localField: 'capitalId',    foreignField: '_id',    justOne: true});// tell Mongoose to retreive the virtual fieldscountrySchema.set('toObject', { virtuals: true });countrySchema.set('toJSON', { virtuals: true });// now you can populate your virtual field like it actually exists// the following will return a Country object in the 'capital' fieldCountry.find().populate('capital') 


the approch is correct you should see your data poulated in the products field. make sure you have the correct data and model n


Doing what you want to do technically goes against the convention with regards to using Mongoose. You can keep things simple by just renaming the "productIds" field to "products":

If you think about it, an array of products can be an array of the product id values, or it can be the actual documents. The property name "products" apply correctly to all scenarios, "productIds" do not.

Considering populated documents also has the "_id" property on each of them, there is no need to bloat the JSON with new virtual properties just for the id values - you already have them!

It's highly unlikely that you will get ids when expecting documents or get documents when expecting ids because you are always aware of the times you choose to populate the property and when not. Example: If you are talking to an API endpoint, then that API endpoint will always either return the products populated or not populated, not both randomly. Your front-end is then coded against that!