无法让猫鼬虚拟成为结果对象的一部分 [英] Can't get Mongoose virtuals to be part of the result object
问题描述
b我声明了一个我希望作为其架构查询结果的一部分出现的虚拟,但是当我在对象上执行 console.log 时它没有显示.这是架构:
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;
});
toObject 不应该将虚拟设置为任何查询结果的属性吗?它没有,schema.set("toObject", { virtuals: true }) 也没有.我这样做对吗?
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?
推荐答案
因为您在 console.log
调用中使用了 JSON.stringify
,它会调用 JSON.stringify
模型实例上的 code>toJSON 方法,而不是 toObject
.
Because you're using JSON.stringify
in your console.log
call, that invokes the toJSON
method on the model instance, not toObject
.
所以要么在你的调用中省略 JSON.stringify
:
So either omit the JSON.stringify
in your call:
console.log(results[0]);
或者在架构上设置 toJSON
选项,例如您当前正在设置 toObject
选项.
Or set the toJSON
option on the schema like you're currently setting the toObject
option.
...
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
这篇关于无法让猫鼬虚拟成为结果对象的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!