What is the killer reason for using Mongoose ORM?


Question

I've been using it with a new project, but it is also my first time using MongoDB. Defining a schema seems unnecessary because I thought the upside of mongo was that it didn't need defined schemes. Can't I just save objects on the fly no matter the schema? Then why would I want to? Also the documentation is lacking, making some things I can easily do in the mongo shell harder then they should be.

1
20
9/22/2017 6:01:22 PM

Accepted Answer

The best thing about Mongoose for MongoDB is the fact that you can have built-in automatic validation of the data which you are inserting/updating. Mongoose also gives you the ability to pre-define events to happen, say, before a document gets saved. This is very powerful because it consolidates the code you would have to write, and it places that code where it should be next to the document logic and not in the application logic.

Check out middleware and validation for some examples. alexyoung/Nodepad on Github has some good examples in the models.js file.

20
4/27/2011 2:18:57 AM

Knowing a defined schema beforehand can be handy, because then you can make assumptions that you otherwise might not be able to.

For example, if I have a Post schema, then I can assume that it has a body field and use it as a String without checking its existence.

Granted, even on my well-defined model, I can have the equivalent of a schemaless document inside it, e.g.

mongoose.model('Post', new Schema({
    body: String,
    meta: {}
}));

and then I can very simply add random data to myPost.meta at whim. It provides a very nice balance for me between defined schema and schemaless.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon