Home > Blockchain >  Mongoose: Populate or reference Id on Schema?
Mongoose: Populate or reference Id on Schema?

Time:12-17

I am wondering which is better in terms of performance.

Let's say i have this Menu Schema

{
    restaurant: { type: String, unique: true, required: true },
    color: { type: String, required: true },
}

And i have this Plate Schema

{
    name: { type: String, unique: true, required: true },
}

If i want to get all the plates from the Menu, which option is better?

Associate the Menu with plates like this:

{
        restaurant: { type: String, unique: true, required: true },
        color: { type: String, required: true },
        plates: [
            type: Schema.Types.ObjectId,
            ref: 'plate'
        ]
}

Or like this:

{
        name: { type: String, unique: true, required: true },
        menu: {
            type: Schema.Types.ObjectId,
            ref: 'plate'
        }
}

With the first option, i would use Menu.findById(id).populate('plates') to get the menu and all the plates associted with it. But with the second option, i would use Plate.find({menu: menu_id})

So, which is faster considering that i could have any amount of plates?

And if they are the same, is there a better way of associate Plate and Menu and get plates from Menu?

CodePudding user response:

In terms of the performance, the second one would be faster because the first one would do the $lookup behind the scene (when doing populate), which is actually additional database call.

I would suggest the third option, which would be the best in your use case. That is embedding the plate documents inside the menu document.

{
  restaurant: { type: String, unique: true, required: true },
  color: { type: String, required: true },
  plates: [
    { 
      name: { type: String }
    }
  ]
}

This way, menu document will contain all the information you needed and you can fetch everything with one database call.


Note: There is a limitation of 16MB for each document in the MongoDB. You can for sure store thousands or tens of thousands plates in each menu without a problem. But if you need to store much more in each menu, then you should go with some of your initial setups.

  • Related