Getting Started With MongoDB And Mongoose
ScaleGrid is the only MongoDB hosting solution that lets you manage mongo instances on both public clouds and on premise from a single central console. Try us free for 30 days.
This post was originally featured on the ScaleGrid blog and ranked one of our most popular posts.
If you have other tips on how to get started with MongoDB and Mongoose, please comment below.
What is Mongoose?
Mongoose is an “elegant mongodb object modeling for node.js.” If you have used MongoDB before and tried basic database operations, you might have noticed that MongoDB is “schema less.” When you are looking to implement a more structured database and want to leverage the power of MongoDB, Mongoose is one of the ODM (Object Data Mapping) solutions.
To quickly demonstrate, you run an insert command into a collection named users like:
And right after that you can run:
and MongoDB will never complain about the variation in the number of columns (key value pairs). This is very flexible. But when you want to keep your data more organized and structured, you would need to maintain that in your server code, writing validation, making sure nothing irrelevant is stored in a collection. And this is where Mongoose makes life easy.
“Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more, out of the box.”
Install Node js & MongoDB
To use Mongoose, we need to have Node js installed, you can find info here.
Let us first create a small playground, where we can have fun. Create a new folder named myMongooseApp. And open terminal/prompt here and run:
This will help us in initializing a new node project. Fill it up as required. Next, we will install Mongoose as a dependency to our project. Run:
then start the MongoDB service by running:
Next, create a new file named index.js at the root of the and then open it up in your favorite editor. And add the below code.
Here, we require the mongoose package to connect to the DB, and initialize the connection. The name of our Database is myTestDB.
You should see the connected message. You can also use a node package named nodemon for automatically restarting the node server on changes.
Now, our sandbox is ready to play!
Schemas are like skeletons. The bare bones of how your data collection will look like. If you are dealing with a collection of users, your schema would look something like this:
And if you are dealing with a collection of products, your schema will look something like this:
You can see the drift. When our data is guarded with a schema like this, the possibility of storing garbage data reduces drastically.
Now we got an understanding of schemas, lets try and build a user schema using Mongoose. Back to index.js and add the below code:
Basic User related fields and their schema types. You can find a list of schema types here.
Next, we will create a model from the schema. Add:
Thats it, our User model is ready. We will use this as our base schema to insert users into the database. This way we know that every document in a User collection will have the fields listed on the schema. Lets create a new user instance and save it to DB add:
And you should see something like:
No hassles, no issues. Simple and easy API to interact with Models.
Let’s say that we want each model to have a method named isYounger. This method will return true if age is less than 50, false if greater. We can do this by querying the DB for the current user, then checking the conditioning and the returning true or false.
But what if we want to implement this method to all the models of User schema? This is how we do it in Mongoose:
On line 21, we add the method definition. And the result on line 39 will be false. This is a simple, handy way of adding methods to your Schema, making it more Object Oriented.
In case you have a password field, you can add a method like encryptPassword(), to encrypt password and comparePassword(), to compare the passwords at login to the userSchema itself. You can read more about password Authentication here.
Out of box Mongoose also provides a few options when the schema is created. For example, if you take a look at the below schema declaration, we are passing an option:
strict:false. Strict option is true by default and it does not allow the ‘non-schema’ key value pairs to be saved. Example:
will be saved, whereas:
All of the above will be saved minus the bucketList array, because it was not declared as part of schema. So, no client who consumes your services will be able to dump invalid data into your collections.
Another cool option is collection. If you don’t want your model name to be the same as collection name, you can pass the name as an option like
You can find a list of other options here.
With Mongoose, You can also add events to your schemas like pre save or post save, where you can perform validations or process data or run other queries in the respective events. These methods are called as Middlewares.
A simple example can be a parallel middleware like:
You can read more about middlewares here. In our next post we will talk more about using Yeoman to automatically generate scaffolding for your Mongodb projects.
Let us know how we can help you, share your projects in the comments or visit our site.