Mongoose: 支持嵌套虚拟,子文档中的虚拟

创建于 2011-02-12  ·  6评论  ·  资料来源: Automattic/mongoose

var Page = new Schema({
    author: {
        first_name: String
      , last_name: String
    }
});
Page.virtual("author.full_name").get(function() {
    return this.author.first_name + " " + this.author.last_name;
});

// Later
myPage = new Page({author: {first_name: "John", last_name: "Doe"}});
myPage.author.full_name; // == undefined
myPage.get("author.full_name"); // == "John Doe"

我还没有尝试用自己的虚拟为作者创建一个新的模式。 也许这会起作用,但根据其他问题报告,子模式在数组 atm 中以最佳方式工作,而不是作为普通的子文档。

查看源代码,这看起来并非不可能,只是在将虚拟添加到模式树时缺少一些巧妙的 split(".") 逻辑。

get 方法暂时可以正常工作,但最好使用其他语法。 :)

最有用的评论

上面的解决方案有效,但您还需要为嵌套模式设置虚拟:

Variation.set('toJSON', {
    virtuals: true
});

所有6条评论

当然,此修复程序也应应用于子文档上的方法

如果作者是一个数组怎么办? 我们可以在每个阵列上做一个虚拟吗?

+1 支持数组

+100 对数组的支持

想通了:。

var Variation = new Schema({
  label: {
    type: String
  }
});

// Virtual must be defined before the subschema is assigned to parent schema
Variation.virtual("name").get(function() {

  // Parent is accessible
  var parent = this.parent();
  return parent.title + ' ' + this.label;
});


var Product = new Schema({
  title: {
    type: String
  }

  variations: {
    type: [Variation]
  }
});

上面的解决方案有效,但您还需要为嵌套模式设置虚拟:

Variation.set('toJSON', {
    virtuals: true
});
此页面是否有帮助?
0 / 5 - 0 等级