I am developing a nodejs program and I am facing a problem, I have a mongo schema that is a list of objects :
players: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
But this ref: 'User' isnt enough for what I need. This "players" have the possibility to recieve the object 'User' or the object 'Team' for example. But how can I declare it? Should I delete the "ref" parameter?
One information is: If I put one "User" on this players attributes, I will not put any other type, all objects will be users, the same thing for "Team". But I will know if will be list of teams or list of users, at the time I will create the object.
So how can I declare it?
Thank you
const documentSchema = new Schema({
referencedAttributeId: {
type: Schema.Types.ObjectId,
refPath: 'onModel'
},
onModel: {
type: String,
required: true,
enum: ['Collection1', 'Collection2']
}
});
Now this collection has attribute named referencedAttributeId which links to two collections ('Collection1', 'Collection2'). Whenever you use .populate() function, mongoose will automatically get referenced data.
const data = await CollectionName.find().populate('referencedAttributeId','attributeName1 attributeName2')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With