【问题标题】:Mongoose virtuals in array of subdocument子文档数组中的猫鼬虚拟
【发布时间】:2020-11-18 18:57:38
【问题描述】:

有没有办法“获取”子文档中文档字段的值? 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] 
})

【问题讨论】:

    标签: node.js express mongoose mongoose-schema


    【解决方案1】:

    您也可以为此使用虚拟。

    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()) 来查看虚拟对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2019-10-06
      • 2020-08-05
      • 2016-06-05
      • 2015-06-03
      • 2012-11-07
      • 2019-08-09
      相关资源
      最近更新 更多