Home > Software engineering >  Which relation in MongoDB is better?
Which relation in MongoDB is better?

Time:05-09

For my whole projects I have relationed my multiple collection as this.

User model

Name:string, email:string, password:string,
vehicles:[{
  "vehicleId", "vehicleId"
}]     

Vehicle model

vehicleId:string,
vehicleName: string    

Is this is the best method ?

I am using this method becuase in mongoose I can write user.vehicle.populate() to get all the vehicle data

CodePudding user response:

It depends on the amount of entries there will be in the vehicles array.

If you plan to store less than a couple of hundreds vehicles, embedding dependancies in an array is the best solution because it allows to retrieve all your user data at once.

That means you don't even have to store only the vehicle's id in the array, you can just put the whole object. This part depends on the way your application has to access the data:

  • If you don't ever use the vehicles independantly of the users, then embedding the whole vehicle documents is good because you can retrieve all your data at once without joining two different collections (expensive).
  • Although if you do need those collections independantly, prefer including only the id in the array, because it will simplify your vehicle queries.

On the other hand, if vehicles start to stack up to thousands, embedding them all in an array is definetly not fine and you will have performances issues as your data amount grows. You should then use foreign keys to reference the user documents in the vehicle documents.

This video is the best resource I know on mongodb schema design : https://youtu.be/leNCfU5SYR8

  • Related