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 :

Installation :

npm install mongoose

Importing :

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

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

Connecting to MongoDB :

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

Defining a model :

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 :

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 :

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 :

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

DELETE Data :

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

Thank you for reading.