CRUD Operations with MongoDB & Mongoose

Notice: A non well formed numeric value encountered in /home/ghadeerr/public_html/ on line 118

Today we are going to take a look at how we can save data to a mongo database using mongoose. By using mongoose, we are able to model data in our application very cleanly and abstract away low-level mongo operations. Mongoose also gives us the ability to model the data in our applications easily.

We will focus on setting up our models and performing basic CRUD operations in this article

Gettings Setup

Before we begin, we’ll need to install mongoose and setup our database connection

The next thing to do is create a mongo db database, my preference is to use mlabs, however a local connection works just as well. Like all well architected applications, we will extract our connection parameters to environment variables so that our application can easily scale and be deployed.

This function allows us to connect to our database. Notice we are using ES6 string interpolation to concatenate together the variables that make up our connection string.

Now let’s work on our models and demonstrate CRUD operations. A mongoose model will have properties that have a type, these properties make up the model’s Schema.


Now you’ll notice that we are requiring some properties of the Schema, while with others we are not. When we try to save a User to the database without an email or password, we will get an error.

Next, we are going perform our CRUD operations.


Saving a model is done with the create function. Mongoose does not use promises, instead it relies on callbacks. The first parameter to the callback represents an error. The error will have with a message property or will be null if an error did not occur. The second parameter to the callback is our created document. After our document is created, you will notice an _id property, this property is the id we can use when we want to look up the document.


Now that we have saved our user object, let’s have a look and see how we can retrieve it. If we have the user, then we can find the user using the mongoose id.

If we don’t have the mongoose id, we can use the findOne function that will allow us to search for the user by specifying search parameters


Now let’s update the user’s first and last name. One way of doing this is by calling the findByIdAndUpdate, pass the user’s id with the new firstName and lastName


Finally, let’s look at deleting a user. Similar to the update function, we can use the user’s id to remove the record from the mongo collection by calling the findByIdAndRemove function

We have barely scratched the surface on mongoose, but this should give you a taste of how it works. In later posts, we will go into some nuisances of mongoose and look into more complicated pieces of functionality.

If you enjoyed this article, enter your email below to get free updates!