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.
The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application.
Mongoose: Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Waterline: An ORM extracted from the Express-based Sails web framework. It provides a uniform API for accessing numerous different databases, including Redis, MySQL, LDAP, MongoDB, and Postgres.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. MongoDB is a schema-less NoSQL document database.
Mongoose allows users to conveniently create and manage data in MongoDB. While it is possible to manage data, define schemas, etc. using MongoDB APIs, it is quite difficult to do so. Hence, Mongoose has made lives easier.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With