简体   繁体   中英

Mongoose: Populate or reference Id on Schema?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM