question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

how to populate virtual fields in the response of create document

See original GitHub issue

https://github.com/Automattic/mongoose/issues/3225

as per this its working perfect the data from field is getting populated in virtual field in case of getById

var countrySchema = new mongoose.Schema({
    capitalId: {type:String}
});

countrySchema.virtual('capital',{
    ref: 'City',
    localField: 'capitalId',
    foreignField: '_id',
    justOne: true
});

countrySchema.set('toObject', { virtuals: true });
countrySchema.set('toJSON', { virtuals: true });

Country.find().populate('capital') 

======================

what about create case after create in response if i want the virtual field to get populated.

i added following code for that but its not working

countrySchema.post(“save”, async function(){ await this.populate({ path: “capital”, model: “City” }).execPopulate(); })

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
NitinMagdumcommented, Mar 15, 2021
0reactions
indraraj26commented, Mar 13, 2021

@NitinMagdum whatever you will do you are going to make another request in order to get the data from another collection.

As per your initial post, This will work

const mongoose = require('mongoose');

let CountrySchema = new mongoose.Schema({
    capitalId: mongoose.Types.ObjectId
}, {
    toJSON: {virtuals: true},
    toObject: {virtuals: true},
});

CountrySchema.virtual('capital', {
    ref: 'City',
    localField:  'capitalId',
    foreignField: '_id',
    justOne: true
})

CountrySchema.post('save', async function() {
   await this.populate('capital').execPopulate();
})

let CitySchema = new mongoose.Schema({
    name: String
});


run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();
 
    const CountryModel = mongoose.model('Country', CountrySchema);
    const CityModel = mongoose.model('City', CitySchema);
    const cityRes = new CityModel({ name: 'Mumbai' });
    const savedCity = await cityRes.save();
    const countryRes = new CountryModel({capitalId: savedCity._id});
    const savedCountry = await countryRes.save();
    console.log(savedCountry, 'savedsavedCountry')
}

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mongoose Virtuals
In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents.
Read more >
Virtual populate mongoose - Stack Overflow
You need an option virtuals: true passed into the schema creation: const tourSchema = new mongoose.Schema({ ... }, { virtuals: true }.
Read more >
How to Use Virtual Fields to Populate a Field ... - Omatic Support
In the IOM profile, on the virtual field column select and set the "Function" to "Copy Field". On the same virtual field, map...
Read more >
How to populate virtuals to a mongoose model using Node.js
Create a folder and add the file main.js. For populating virtual, we have to specify three necessary options:.
Read more >
populate doesn't include virtuals when populate multiple ...
I have set these schema options. resourceSchema.set('toObject', { virtuals: true }); resourceSchema.set('toJSON', { virtuals: true });. User.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found