So I know how to get a single virtual attribute, as stated in the Mongoose docs:
PersonSchema
.virtual('name.full')
.get(function () {
return this.name.first + ' ' + this.name.last;
});
But what if my schema is:
var PersonSchema = new Schema({
name: {
first: String
, last: String
},
arrayAttr: [{
attr1: String,
attr2: String
}]
})
And I want to add a virtual attribute for each nested object in arrayAttr:
PersonSchema.virtual('arrayAttr.full').get(function(){
return attr1+'.'+attr2;
});
Lemme know if I missed something here.
You need to define a separate schema for the elements of attrArray
and add the virtual attribute to that schema.
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]
});
First of all you should write
this.some_attr
instead of some_attr
And you can't acces this.attr because there are in arrayAttr. So you can do for example:
this.arrayAttr[0].attr1 + "." + this.arrayAttr[0].attr2
This is not safe because arrayAttr can be empty