无法使Mongoose虚拟机成为结果对象的一部分 [英] Can't get Mongoose virtuals to be part of the result object
问题描述
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屋!