Mongoose模式多引用一个属性

25

如何为一个mongoose模型中的某个属性编写多个引用,类似于以下代码(但是错误的):

var Schema = mongoose.Schema;
var PeopleSchema = new Schema({
    peopleType:{
        type: Schema.Types.ObjectId,
        ref: ['A', 'B'] /*or 'A, B'*/
    }
})

这并不是很有意义,因为Mongoose如何知道要引用哪个模型来获取给定文档?您能否提供更多关于您尝试做什么的细节? - JohnnyHK
好的。比如说,我有两种商品类型,AGoods模型和BGoods模型。我还有一个Goods模型来保存它们所有的信息(只保存引用)。所以当我查找一个商品时,我会在Goods模型中搜索,如果找到了,就会从AGoods或BGoods中填充真实的商品信息。 - 幻影枫韵
你找到了一种方法来做这件事吗? - timhc22
3个回答

40

你应该向你的模型中添加字符串字段,并将外部模型名称存储在其中,并使用refPath属性 - Mongoose动态引用

var Schema = mongoose.Schema;
var PeopleSchema = new Schema({
    externalModelType:{
        type: String
    },
    peopleType:{
        type: Schema.Types.ObjectId,
        refPath: 'externalModelType'
    }
})
现在Mongoose会使用对应模型中的对象填充peopleType字段。

1
那么他应该添加两个字符串字段来引用模型A和B? - AG_HIHI

6
在当前版本的Mongoose中,我仍然没有看到您想要的语法实现多重引用。但是,您可以使用“跨数据库填充”方法的一部分,该方法在此处描述:这里。我们只需将填充逻辑移到显式的填充方法变体中即可。
var PeopleSchema = new Schema({
    peopleType:{
        //Just ObjectId here, without ref
        type: mongoose.Schema.Types.ObjectId, required: true,
    },
    modelNameOfThePeopleType:{
        type: mongoose.Schema.Types.String, required: true
    }
})

//And after that
var People = mongoose.model('People', PeopleSchema);
People.findById(_id)
    .then(function(person) {
        return person.populate({ path: 'peopleType',
            model: person.modelNameOfThePeopleType });
    })
    .then(populatedPerson) {
        //Here peopleType populated
    }
...

0
你可以通过refPath使用动态引用来实现这一点。
const commentSchema = new Schema({
body: { type: String, required: true },
doc: {
    type: Schema.Types.ObjectId,
    required: true,
    // Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
    // will look at the `docModel` property to find the right model.
    refPath: 'docModel'
},
docModel: {
    type: String,
    required: true,
    enum: ['BlogPost', 'Product']
}

});

从mongoose文档中获取,通过refPath动态引用的mongoose文档链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接