在猫鼬模式中添加“虚拟"变量? [英] Adding 'virtual' variables to a mongoose schema?

查看:59
本文介绍了在猫鼬模式中添加“虚拟"变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下文档架构:

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?

推荐答案

在猫鼬中完全有可能.
检查这个例子,取自他们的文档:

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

在上面的示例中,该属性没有设置器.要为此虚拟机设置二传手,请执行以下操作:

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屋!

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