无法使Mongoose虚拟机成为结果对象的一部分 [英] Can't get Mongoose virtuals to be part of the result object

查看:59
本文介绍了无法使Mongoose虚拟机成为结果对象的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

b我声明了一个虚拟对象,该虚拟对象要作为其架构查询结果的一部分出现,但是当我在对象上执行console.log时,它并没有显示出来.这是模式:

var schema = new mongoose.Schema(
{
    Name: { type: String }
},
{
    toObject: { virtuals: true }
});

schema.virtual("Greet").get(function()
{
    return "My name is " + this.Name;
});

该toObject不应将virtual设置为任何查询结果的属性吗?它没有,schema.set("toObject",{virtuals:true})也没有.我这样做正确吗?

解决方案

由于您在console.log调用中使用了JSON.stringify,因此会在模型实例而不是toObject上调用toJSON方法. /p>

因此您可以在通话中省略JSON.stringify:

console.log(results[0]);

或在当前设置的架构上设置 toJSON 选项toObject选项.

...
{
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

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 schema:

var schema = new mongoose.Schema(
{
    Name: { type: String }
},
{
    toObject: { virtuals: true }
});

schema.virtual("Greet").get(function()
{
    return "My name is " + this.Name;
});

Should that toObject not set the virtual as a property of the results of any queries? It does not, nor does schema.set("toObject", { virtuals: true }). Am I doing this right?

解决方案

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

这篇关于无法使Mongoose虚拟机成为结果对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆