CRUD Operations using Mongoose and MongoDB

Minhajul Alam
6 min readSep 8, 2020

--

MongoDB is an open-source document database. It stores data in flexible, JSON like documents.

In relational databases we have tables and row, but in MongoDB we have collections and documents. A document can contain sub-documents. We don’t have relationships between documents.

CRUD Operations using Mongoose and MongoDB

Installing MongoDB on Linux, macOS and Windows

To install MongoDB into you computer, follow the instructions provided into MongoDB official documentation.

For Linux here.

For macOS here.

For Windows here.

MongoDB Compass

The GUI for MongoDB. You can easily explore and manipulate your MongoDB data. Download from here.

Creating environment

Create an empty folder. Open terminal into the folder. Run the command below. It will create package.json file into the folder.

npm init --yes

Open the folder using your favorite code editor.

Connecting to MongoDB

Install mongoose using the command below.

npm install mongoose

mongoose gives us a simple api to work with mongodb. This mongoose object has a method called connect. We use this method to connect with mongodb. We pass connection string in the connect method. This connect method returns a promise.

mongoose
.connect(“mongodb://localhost/YourDatabaseName”)
.then(() => console.log(“Connection established.”))
.catch((err) => console.log(“Could not connect to mongodb.”, err));

Schemas

A document schema is a JSON object that allows you to define the shape and content of documents and embedded documents in a mongoose Collection.

Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. We can create a schema using mongoose.Schema class by passing an object.

const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
});

We can add default values in the schema using this object.

{ type: SchemaType, default: YourDefaultValue}

Schema Types:

Supported types are : String, Number, Date, Buffer, Boolean, ObjectID, Array

Models

Once we have a schema, we need to compile it into a model. A model is like a class. It’s a blueprint for creating objects.

We can create a model by using model() method. This model method have two parameters. First is the Collection name in singular form and second one is the schema.

const Course = mongoose.model(“Course”, courseSchema);

This mongoose.model() returns a Class. Now we are going to create instance of Course class.

const course = new Course({
name: “MongoDB course”,
author: “Minhajul Alam”,
tags: [“MongoDB”, “Database”],
isPublished: true,
price: Number
});

Saving a Document

After creating an instance of our Course class, it’s time to save it into our database. We will use save() method.

const result = course.save();

This save method returns a promise. So we have to wait to get the result. For this reason we will use await keyword in course.save() method and wrap it with async function.

async function createCourse(){
const course = new Course({
name: “MongoDB course”,
author: “Minhajul Alam”,
tags: [“MongoDB”, “Database”],
isPublished: true
price: Number
});
const result = await course.save();
console.log(result);
}createCourse();

Querying Documents

We can find all the courses in the Collection using find() method.

async function getCourses(){
const courses = await Course.find();
console.log(courses);
}

We can limit the document number in the result using limit() method.

async function getCourses(){
const courses = await Course.find().limit(10);
console.log(courses);
}

We can sort the result using sort() method. Below this code will return all the courses based on their name in ascending order. 1 is for ascending and -1 for descending order.

async function getCourses(){
const courses = await Course.find().sort({name: 1});
console.log(courses);
}

We can select which document information to show in the result by using select() method. Below this code will return all the courses with the information of name and author.

async function getCourses(){
const courses = await Course.find().select({name: 1, author: 1});
console.log(courses);
}

We can filter the result by passing an object into the find() method. Like we can get all the courses of Minhajul Alam that are published.

async function getCourses(){
const courses = await Course.find({
author: “Minhajul Alam”,
isPublished: true,
})
console.log(courses);
};

Comparison Query Operator

There are some comparison query operator.

eq (equal to)
ne (not equal)
gt (greater than)
gte (greater than or equal to)
lt (less than)
lte (less than or equal to)
in
nin (not in)

We can get all the courses that has a price of 10 by passing {price: 10} object into the find() method.

async function getCourses(){
const courses = await Course.find({price: 10});
console.log(courses);
}

We can get all the courses that has price between 10 and 20 using the $gte and $lte comparison operator.

async function getCourses(){
const courses = await Course.find({price: {$gte: 10, $lte: 20});
console.log(courses);
}

We can get all the courses that has price of 10, 20, 30 using the $in comparison operator.

async function getCourses(){
const courses = await Course.find({price: {$in: [10,20,30]});
}

Logical Query Operator

There are some logical query operator.

and
or

We can get all the courses of Minhajul Alam or the courses that are published.

async function getCourses(){    const courses = await Course
.find()
.or([{author: “Minhajul Alam”},{isPublished: true}]);
console.log(courses);
}

Regular Expressions

We can find all the courses that authors starts with ‘Minhaj’. We can mark it case insensitive using ‘i’. Here ‘^’ means, starting of a string.

async function getCourses(){
const courses = await Course.find({author: /^Minhaj/i});
}

We can find all the courses that authors ends with Alam. Here $ means, ending to a string.

async function getCourses(){
const courses = await Course.find({author: /Alam$/i});
}

We can find all the courses that authors contain Minhajul anywhere in the string. Here, ‘.*’ means zero or many characters.

async function getCourses(){
const courses = await Course.find({author: /.*Minhajul.*/i});
}

Counting

We can find number of records in a result using count() method.

async function getCourses(){
const courses = await Course.find().count();
}

Skip

We can skip some documents using skip() method.

async function getCourses(){
const courses = await Course.find().skip(10);
}

Updating Documents — Query First

In query first approach, first we check if the course present in the collection using id. If the course not present we return, else we update information of that document.

To find the record in the collection we use findById() method and for updating information of the record we use set() method.

async function updateCourse(id){
const result = await Course.findById(id);
if(!course)
return;

course.set({
isPublished: true,
author: 'John Doe'
})
const result = await course.save();
console.log(result);
}

Updating a Document — Update First

If we don’t need the user input to update something or if we want to update many records at once we can use update first approach.

In the code below, we updated all the courses that are not published yet. The result will be how many documents are changed.

async function updateCourse(){
const result = await Course.update(
{ isPublished: false},
{ $set : {isPublished: true} });
console.log(result);
}

If we want to get the document that we will update we have to use findByIdAndUpdate() method.

async function updateCourses(){
const result = await Course.findByIdAndUpdate(
{ _id: id},
{ $set : {isPublished: true} });
console.log(result);
}

If we want to get the updated document we have to add {new: true} in the method.

async function updateCourse(){
const result = await Course.findByIdAndUpdate(
{ _id: id},
{ $set : {isPublished: true} },
{new: true} );
console.log(result);
}

Removing Documents

To delete a document we use deleteOne() function that takes a query object.

async function deleteCourse(){
const result = await Course.deleteOne({_id: id});
console.log(result);
}

If we want to delete multiple documents, we will use deleleMany() function.

async function deleteCourses(){
const result = await Course.deleteMany({isPublished: false});
console.log(result);
}

If we want to delete a document and want to get the deleted document, we have to use findByIdAndRemove() function.

async function deleteCours(){
const course = await Course.findByIdAndRemove(id);
console.log(course);
}

--

--