我正在尝试学习MongoDB/Node,我注意到在一个schema中,我经常看到像这样的东西:
toObject: { virtuals: true }
toJSON: { virtuals: true }
这两行代码是什么意思?
我正在尝试学习MongoDB/Node,我注意到在一个schema中,我经常看到像这样的东西:
toObject: { virtuals: true }
toJSON: { virtuals: true }
这两行代码是什么意思?
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
var Person = mongoose.model( "Person", personSchema );
但是假设你只想“存储”这些属性,然后有一个可以在代码中访问的名为“fullname”的东西。这就是“虚拟属性”发挥作用的地方:
personSchema.virtual("name.full").get(function () {
return this.name.first + ' ' + this.name.last;
});
var bad = new Person({
name: { "first": "Walter", "last": "White" }
});
console.log("%s is insane", bad.name.full); // Walter White is insane
name.full
实际上并不存在于数据中,它只是代码中的模式表示。但当然,“绑定”到一个函数,该函数使用对象中实际存在的数据制作方法,根据方法中的代码组合两个字段返回一个值。toObject(): This produces a "plain" or "raw" representation of the object data without all the other "mongoose magic" parts of the extended object. But the purpose of "virtuals" is to make those methods part of the object returned. Basically just the plain object, called as:
var model = Model.new({ "name": { "first": "Walter", "last": "White" });
console.log( model.toObject() );
toJSON(): You can call this method explicitly and just as shown above, but it's most common usage is from a JSON parser like below where it is implicitly called. The same principles apply as above. The "virtuals" includes the result of those methods in the serialized output, such as:
var model = Model.new({ "name": { "first": "Walter", "last": "White" });
JSON.stringify( model, undefined, 2 );
.toJSON()
方法。配置告诉该方法不仅包括对象中存在的数据或"字段",还要包括定义的"虚拟"方法及其输出结果。同样适用于.toObject()
。