2016-08-30 108 views
0

我有一个查询模式:猫鼬动态子文档模式

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 } 
}); 

回答

1

,你可以让你的datatype : ObjectId没有定义模式中的任何引用,当你要填充这些,从不同collection使用pathmodelpopulatepopulate,但你必须有一个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){...}); 
} 
+0

尼斯,这个作品真的很好。 – OllyBarca