子文档数组中的猫鼬虚拟

时间:2020-07-29 08:19:15

标签: node.js express mongoose mongoose-schema

有没有一种方法可以“获取”子文档中文档字段的值? book_id在主文档中,如何在此处获取其价值 '''

const ExtraElements_Schema =  new Schema({
    label : {type : String, requires : true},
    page : {type : Number},
    id_resource : {type : Number, required : true},
    description : {type : String}
},{toJSON : {virtuals : true , getters : true}})

ExtraElements_Schema.virtual('path').get(function(){
    const host = global.gConfig.thisServerHost;
    return `${host}/${this.book_id???}/${this.id_resource}`
})

const Extra_Schema =  new Schema({
    label : {type : String, required : true},
    book_id : {type : Number},
    id_extra : {type : Number, required : true},
    extras : [ExtraElements_Schema] 
})

1 个答案:

答案 0 :(得分:0)

您也可以为此使用虚拟机。

ExtraElements_Schema.virtual('book', {
  ref: bookTableName,
  localField: 'book_id',
  foreignField: '_id', // Change this if it's not the id that is saved
  justOne: true
});

有一件事让我有些烦恼,我无法使用console.log看到虚拟机,我应该始终使用console.log(model.toJSON())来查看虚拟机