NodeJs CRUD Operations Using Mongoose

Before we dive into the major operations and functionality of mongoose, let’s get a brief idea about what is mongoose and how it help us to make our NodeJs project more flexible and user friendly.

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.It is an Object Document Mapper(ODM) that allows us to define objects with strongly-typed-schema that is mapped to a MongoDB document. Mongoose supports all the CRUD operations.

Prerequisite :

You need to install NodeJs and MongoDB

Installation :

Install mongoose through npm using the below command:

Importing :

Connecting to MongoDB :

First, we need to define a connection. For that you should use mongoose.connect and it take mongodb://URI, host, port, database and options. The following code snippet shows how to connect to a database called fruitsDB.

Defining a model :

Models can be defined through the Schema interface. Aside from defining the structure of your documents, a Schema can handles validators and many more. The bellow code snippet show how to add fruit schema with a required field name and validate rating between 1 and 10.

You can access to your define model through mongoose.model

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name.

CREATE Data :

Once we have the model, we can instantiate and save it as follows.

READ Data :

We can find documents from same collection using .find() function.

To retrieve a single record or the first matched document we can use the function .findOne(). First we need to provide query and it returns a callback.

UPDATE Data :

To update your data we can use .updateOne() function and you need to send query and what you want to update and function return a callback.

DELETE Data :

You can delete data using .deleteOne() function you need to provide which data you want to delete as a parameter and function return a callback.

Thank you for reading.