【问题标题】:Mongoose dynamic sub document schemaMongoose 动态子文档架构
【发布时间】:2016-08-31 11:02:17
【问题描述】:

我有一个查询模式:

const inquirySchema = new mongoose.Schema({
  client: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Client' }],
  data: dynamicSchema?
}, {
  timestamps: true
});

我想用子文档填充“数据”属性字段,但我希望它接受不同的子文档模式。我有一个“事件”和一个“属性”子模式,可以作为“数据”插入。如何在我的查询模式中允许这样做?看来我必须实际指定它期望的子文档架构......

我的孩子模式:

const eventSchema = new mongoose.Schema({
  name: { min: Number, max: Number },
  date: { type: Date },
  zone: { type: String }
});

const propertySchema = new mongoose.Schema({
  price: { min: Number, max: Number },
  status: { type: String },
  zone: { type: String }
});

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以将data 设置为type : ObjectId 而无需在架构中定义任何引用,并且当您想要填充它们时,请在populatepopulate 中使用pathmodel 从不同的@ 987654327@,但您必须有一个logic 用于选择collectionpopulate 的哪个。

    你可以这样做:

    inquirySchema

    const inquirySchema = new mongoose.Schema({
      client: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Client' }],
      data: { type: mongoose.Schema.Types.ObjectId }
    }, {
      timestamps: true
    });
    

    填充data

    if(isEvent)
    {
        //Populate using Event collection
        Inquiry.find({_id : someID}).
                populate({path : 'data' , model : Event}).
                exec(function(err,docs){...});
    }
    else if(isProperty)
    {
        //Populate using Property collection
        Inquiry.find({_id : someID}).
                populate({path : 'data' , model : Property}).
                exec(function(err,docs){...});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 2013-03-29
      • 2015-04-12
      • 2017-07-05
      • 2012-09-11
      • 2014-11-23
      • 1970-01-01
      • 2017-07-17
      相关资源
      最近更新 更多