Can't get Mongoose virtuals to be part of the result object

后端 未结 3 1903
無奈伤痛
無奈伤痛 2020-12-06 04:14

bI\'m declaring a virtual that I want to appear as part of the results of its schema\'s queries, but it\'s not showing up when I do a console.log on the object. Here\'s the

相关标签:
3条回答
  • 2020-12-06 04:58

    I ended up here doing something really silly. I was using Doc.find instead of Doc.findOne and so I was trying to access the virtual on the document array instead of on the document itself.

    0 讨论(0)
  • 2020-12-06 05:00

    My mistake was not including the needed fields in the query. If they are not selected in projection, then mongoose does not knows how to combine/calculate the virtual field.

    0 讨论(0)
  • 2020-12-06 05:05

    Because you're using JSON.stringify in your console.log call, that invokes the toJSON method on the model instance, not toObject.

    So either omit the JSON.stringify in your call:

    console.log(results[0]);
    

    Or set the toJSON option on the schema like you're currently setting the toObject option.

    ...
    {
        toObject: { virtuals: true },
        toJSON: { virtuals: true }
    });
    
    0 讨论(0)
提交回复
热议问题