Express.js and Mongoose model relationships - in model or router? Express.js and Mongoose model relationships - in model or router? mongoose mongoose

Express.js and Mongoose model relationships - in model or router?


Do it in the model. Even if you're not creating an enforced relation, storing the actual ID of a related object still changes the model, so there's no reason to leave the logic in the router.

MongoDB (and Mongoose) doesn't have referential integrity like relational databases do. This means that the database will not give you an error if you insert a relation to an object which doesn't exist. It lets the application code handle those relations.

Mongoose is an attempt to bring structure to an otherwise pretty liberal nosql DB. As such, it offers an ability to create such relations with the ObjectId schema type.

Read the following SO answer for more info: https://stackoverflow.com/a/7813331/1801