I have an app where one document wants to reference another document, the catch here is the other documents could be in two different collections. is there a way to do it, keeping in mind I'm going to have to populate them when they are fetched.
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,
})
The solution I'm not try to do is to create two fields one for the schemaOne and the other for schemaTwo. but this I think will create more complexity.
You can use refPath. This allows you to have a field in schemaThree
that specifies which model to use when you populate.
const schemaThree = new Schema({
someId: {
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('someId');
When you create a document with ModelThree
just make sure you save the ObjectId
in the someId
field of whichever schema relates to that Objectid
in the modelNameSpecifier
as either ModelOne
for schemaOne
or ModelTwo
for schemaTwo
.