将“虚拟"变量添加到猫鼬模式? [英] Adding 'virtual' variables to a mongoose schema?
本文介绍了将“虚拟"变量添加到猫鼬模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下文档架构:
var pageSchema = new Schema({
name: String
, desc: String
, url: String
})
现在,在我的应用程序中,我还希望在对象中包含页面的 html 源代码,但我不想将其存储在 db 中.
Now, in my application I would like to also have the html source of the page inside the object, but I do not want to store it in the db.
我应该创建一个引用 db 文档的本地"增强对象吗?
Should I create a "local" enhanced object which has a reference to the db document?
function Page (docModel, html) {
this._docModel = docModel
this._html = html
}
有没有办法通过添加虚拟"字段直接使用文档模型?
Is there a way to use the document model directly by adding a "virtual" field?
推荐答案
这在 mongoose 中完全可以实现.
检查这个例子,取自他们的文档:
This is perfectly possible in mongoose.
Check this example, taken from their documentation:
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
personSchema.virtual('name.full').get(function () {
return this.name.first + ' ' + this.name.last;
});
console.log('%s is insane', bad.name.full); // Walter White is insane
在上面的例子中,属性没有设置器.要为此虚拟设置一个 setter,请执行以下操作:
In the above example, the property would not have a setter. To have a setter for this virtual, do this:
personSchema.virtual('name.full').get(function () {
return this.name.full;
}).set(function(name) {
var split = name.split(' ');
this.name.first = split[0];
this.name.last = split[1];
});
这篇关于将“虚拟"变量添加到猫鼬模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文