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.

Add note about `console.log()` with populated virtuals to docs

See original GitHub issue

Do you want to request a feature or report a bug? bug

What is the current behavior? Case 1: It does not return the populate field if i populate just after the save

const x = await y.populate('poster').execPopulate();
 console.log(x)

Case2: If i add {toObject: {virtuals: true}, toJSON: {virtuals: true}} this in product Schema i get this output

{
  _id: 6152b575fdd5743bc8fb3bed,
  product_name: 'Biscuit',
  owner: 2,
  __v: 0,
  id: '6152b575fdd5743bc8fb3bed'
}

Case 3: with find().populate(‘poster’) it will return the expected result.

If the current behavior is a bug, please provide the steps to reproduce.

const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
    name : {
        type: String,
        required: [true, 'Name is required']
    },
    myId: {
        type: Number,
        required: [true, 'myId is required']
    }
});

let ProductSchema = new mongoose.Schema({
    owner: {type: mongoose.Schema.Types.Number, ref: 'user'},
    product_name: {type:String, required: true}
})


/* {toObject: {virtuals: true}, toJSON: {virtuals: true}} */
  

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 UserModel = mongoose.model('user', UserSchema);
    const ProductModel = mongoose.model('product', ProductSchema);

    ProductSchema.virtual('poster', {
        ref: 'user',
        localField: 'owner',
        foreignField: 'myId',
      }); 

    const userRes = new UserModel({ name: 'Alexa', myId: 2});
    await userRes.save();
    const productRes = new ProductModel({product_name: 'Biscuit', owner: 2});
    const y = await productRes.save()
    const x = await y.populate('poster').execPopulate();
    console.log(x)
    /* 
     with find populate it will work
    */
    // const findPopulateRes = await ProductModel.find().populate('poster');
    // console.log(findPopulateRes)
}

What is the expected behavior?

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version. node - v14.17.1 mongodb - 4.2 mongoose - 5.9.22

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
vkarpov15commented, Oct 19, 2021

@indraraj26 I took a closer look and this is expected behavior because you’re adding ProductSchema.virtual('poster') after creating your product model with mongoose.model('Product', ProductSchema).

From the model docs:

The .model() function makes a copy of schema. Make sure that you’ve added everything you want to schema, including hooks, before calling .model()!

0reactions
indraraj26commented, Oct 12, 2021

Hi @vkarpov15,

even with virtual: true on schema doesn’t work as you can see, i have attached the output in main thread.

Could you please try it once with my script.

Thank you

Read more comments on GitHub >

github_iconTop Results From Across the Web

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: ref: It contains the name...
Read more >
Populate on virtuals is not working. · Issue #11047 - GitHub
If you want populate virtuals to show up when using functions like Express' res.json() function or console.log(), set the virtuals: true ...
Read more >
Writing, Viewing, and Responding to Logs | Cloud Functions ...
Logs written to stdout or stderr will appear automatically in the Google Cloud console. For more advanced logging, use the Cloud Logging client...
Read more >
Mongoose v6.8.2: Query Population
Mongoose has a more powerful alternative called populate() , which lets you reference documents in other collections. Population is the process of ...
Read more >
Mongoosejs virtual populate - node.js - Stack Overflow
Figured out what the problem was. By default, the virtual fields are not included in the output. After adding this in circle schema:...
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