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

久未见 提交于 2019-11-27 22:44:33

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 }
});

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!