Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic Reference in node js mongodb

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

like image 452
Vinicius Martin Avatar asked May 13 '26 13:05

Vinicius Martin


1 Answers

    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')
like image 93
Saurav Solanki Avatar answered May 15 '26 04:05

Saurav Solanki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!