获取对象数组中每个嵌套对象的虚拟属性?

dae*_*s_j 11 mongoose mongodb node.js express

所以我知道如何获得单个虚拟属性,如Mongoose文档中所述:

PersonSchema
 .virtual('name.full')
 .get(function () {
   return this.name.first + ' ' + this.name.last;
});
Run Code Online (Sandbox Code Playgroud)

但是如果我的架构是:

var PersonSchema = new Schema({
    name: {
      first: String
    , last: String
    },

    arrayAttr: [{
      attr1: String,
      attr2: String
    }]
})
Run Code Online (Sandbox Code Playgroud)

我想为arrayAttr中的每个嵌套对象添加一个虚拟属性:

PersonSchema.virtual('arrayAttr.full').get(function(){
    return attr1+'.'+attr2;
});
Run Code Online (Sandbox Code Playgroud)

Lemme知道我在这里错过了什么.

Joh*_*yHK 23

您需要为元素定义单独的模式attrArray,并将虚拟属性添加到该模式.

var AttrSchema = new Schema({
    attr1: String,
    attr2: String
});
AttrSchema.virtual('full').get(function() {
    return this.attr1 + '.' + this.attr2;
});

var PersonSchema = new Schema({
    name: {
      first: String
    , last: String
    },
    arrayAttr: [AttrSchema]
});
Run Code Online (Sandbox Code Playgroud)


Jan*_* S. 6

当然,你可以定义一个额外的架构,但是mongoose已经为你做了这个.

它存储在

PersonSchema.path('arrayAttr').schema
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过将虚拟添加到此架构来设置虚拟

PersonSchema.path('arrayAttr').schema.virtual('full').get(function() {
  return this.attr1 + '.' + this.attr2
})
Run Code Online (Sandbox Code Playgroud)

  • 如果 `arrayAttr` 是一个对象数组。this 指的是哪个对象?或者“full”现在是“arrayAttr”内每个对象的新属性或键? (2认同)
  • full是每个arrayAttr对象上的新虚拟属性. (2认同)

Bor*_*vic 0

首先你应该写

this.some_attr代替some_attr

并且您无法访问 this.attr 因为 arrayAttr 中有。所以你可以这样做:

this.arrayAttr[0].attr1 + "." + this.arrayAttr[0].attr2
Run Code Online (Sandbox Code Playgroud)

这是不安全的,因为 arrayAttr 可以为空