MongoDB 中的参考

问题描述 投票:0回答:1

我有一个应用程序,其中一个文档想要引用另一个文档,这里的问题是其他文档可能位于两个不同的集合中。有没有办法做到这一点,请记住,在获取它们时我必须填充它们。

const schemaOne = new Schema({
   name: string,
// other fields
})

const schemaTwo = new Schema({
   name: string
// other fields
})

const schemaThree = new Schema({
// I want to reference a document from schemaOne or two in one field
   someId: ObjectId,
})

我没有尝试做的解决方案是创建两个字段,一个用于 schemaOne,另一个用于 schemaTwo。但我认为这会带来更多的复杂性。

javascript node.js mongodb mongoose
1个回答
0
投票

您可以使用refPath。这允许您在

schemaThree
中拥有一个字段,指定您在 populate 时使用哪个模型。

const schemaThree = new Schema({
   type: Schema.Types.ObjectId,
   refPath: 'modelNameSpecifier', //< this is used during populate()
   modelNameSpecifier: {
    type: String,
    required: true,
    enum: ['ModelOne', 'ModelTwo']
  }
});

const docs = await ModelThree.find({}).populate('modelNameSpecifier');

当您使用源自

schemaOne
schemaTwo
的模型创建文档时,请确保将其保存在
modelNameSpecifier
字段中为
ModelOne
ModelTwo

© www.soinside.com 2019 - 2024. All rights reserved.