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:

npm install mongoose

Importing :

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

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.

mongoose.connect("mongodb://localhost:27017/fruitsDB",{
useNewUrlParser: true,
useUnifiedTopology: true
});

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.

const fruitSchema = new mongoose.Schema({
name:{
type:String,
required:[true,"Please check your data"]
},
rating:{
type:Number,
min:1,
max:10
},
review:String
});

You can access to your define model through mongoose.model

const Fruit = mongoose.model("Fruit",fruitSchema);

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.

const orange = new Fruit({
name: "Orange",
rating:7,
review:"Pretty good"
});
orange.save((err)=>{
if(err){
console.log(error)
}else{
"Data inserted successfully"
}
});

READ Data :

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

Fruit.find((err, fruits)=>{
if(err){
console.log(err);
}else{
fruits.forEach((fruit)=>{
console.log(fruit.name);
});
}
});

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.

Fruit.findOne({rating:{$gt: 5}},(err, fruit)=>{
if(err){
console.log(err);
}else{
console.log(fruit.name);
}
});

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.

Fruit.updateOne({name:"Banana"},{rating:5},(err)=>{
if(err){
console.log(err);
}else {
console.log("Updated Successfully.");
}
});

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.

Fruit.deleteOne({name:"Banana"},(err)=>{
if(err){
console.log(err);
}else {
console.log("Deleted Successfully.");
}
});

Thank you for reading.