node.js - Mongoose 子模式数组虚拟

标签 node.js mongoose

我发布了这个问题和答案,希望它能帮助其他人(或者如果有更好的答案)。

如何在数组形式时为 Mongoose 嵌套模式创建虚拟?

这是模式:

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

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

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

我如何想要一个虚拟的变体。似乎如果子文档不是数组,那么我们可以简单地这样做:

Product.virtual('variations.name')...

但这只适用于非数组。

最佳答案

关键是将虚拟定义为子模式的一部分而不是父模式,并且必须在子模式分配给父模式之前完成。可以通过 this.parent() 访问父对象:

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]
  }
});

关于node.js - Mongoose 子模式数组虚拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328481/

相关文章:

node.js - 如何在mongodb中获取每个组的最新N条记录?

javascript - 如何使用 Mongoose 检索多个集合

node.js - Mongo DB 文档只返回 "_id" "$oid"

node.js - 在 SailsJS 中查找当前页面

javascript - 如何在特定事件中自定义 Electron 边框?

node.js - Mongodb、mongoose——动态设置TTL时间

c# - Electron-Edge-JS App.config

node.js - 我如何将 RASA 套件与 NodeJS 集成

javascript - Mongoose 子模式不生成 _id

node.js - 我如何总结我的 mongodb 集合中的值?