Marty Chang
Marty Chang

Reputation: 6619

Why does the model name matter in Mongoose?

Why does the model name matter in Mongoose? I understand that given a model name, Mongoose can try to guess the collection name. However, for this application it seems better and easier to just explicitly specify the collection name instead of the model name.

What else is the model name used for in Mongoose?

Upvotes: 4

Views: 580

Answers (1)

Talha Awan
Talha Awan

Reputation: 4619

Mongoose is an Object Data Mapping (ODM) library for node similar to Object Relational Mapping (ORM) in Ruby on Rails and some other frameworks. Therefore, it follows more or less the same rules (or guidelines, as you can override them):

ORM:

  • Class name capital and singular
  • Table name small and plural
  • Class object mapped/translated to table row and vice versa
  • Class and its objects have methods/hooks

ODM:

  • Model name capital and singular (e.g. User)
  • Collection name small and plural (e.g. users)
  • Model object mapped/translated to collection document and vice versa (e.g. object of model: new User({name: "abc"}), document in collection: {"name": "abc"})
  • Model and its objects have methods/hooks (e.g. pre, post hooks; validations etc)

The mapping is between incompatible types, like an object of Ruby class to a row of SQL table; and a JavaScript object of Mongoose model (can have functions, for instance) to a JSON document of mongodb (valid JSON can't have functions).

Since class and table, model and collection are different entities (though related) and serve different purpose, they are named differently (though similarly). Hence the need of model name in Mongoose!

Upvotes: 1

Related Questions