The aim of this tutorial is to guide you through the process of performing CRUD (Create, Read, Update, Delete) operations using Mongoose in an Express.js application. These are the most common operations that you'll need when interacting with a MongoDB database.
By the end of this tutorial, you will be comfortable in performing CRUD operations, understanding Mongoose schemas, models and the usage of various Mongoose methods for data manipulation.
Firstly, create a new directory for your project and initialize a new Node.js project by running npm init -y
. Install Express.js and Mongoose by running npm install express mongoose
.
Create your server file (app.js) and set up a basic server.
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => console.log(`Server running on port ${port}`));
Next, connect to your MongoDB database using Mongoose.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB...', err));
Before performing CRUD operations, define a Mongoose schema and model. The schema defines the shape of the documents in MongoDB collection and the model provides an interface for CRUD operations.
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [ String ],
date: { type: Date, default: Date.now },
isPublished: Boolean
});
const Course = mongoose.model('Course', courseSchema);
Create a document in MongoDB by instantiating the model and calling the save()
method.
async function createCourse() {
const course = new Course({
name: 'Node.js Course',
author: 'John Doe',
tags: ['node', 'backend'],
isPublished: true
});
const result = await course.save();
console.log(result);
}
createCourse();
You can read documents using various Mongoose methods like find()
, findById()
. These methods return a Query which you can execute by calling exec()
or using async/await.
async function getCourses() {
const courses = await Course
.find({ author: 'John Doe', isPublished: true })
.limit(10)
.sort({ name: 1 })
.select({ name: 1, tags: 1 });
console.log(courses);
}
getCourses();
Update a document using updateOne()
, findByIdAndUpdate()
methods. These methods can directly update the document in the database, or you can first find the document, modify its properties and then save it.
async function updateCourse(id) {
const course = await Course.findById(id);
if (!course) return;
course.isPublished = true;
course.author = 'Another Author';
const result = await course.save();
console.log(result);
}
updateCourse('60c72b5f7284ad3d8c05b2e9');
Delete a document using deleteOne()
, findByIdAndRemove()
methods.
async function deleteCourse(id) {
const result = await Course.deleteOne({ _id: id });
console.log(result);
}
deleteCourse('60c72b5f7284ad3d8c05b2e9');
In this tutorial, we've covered how to perform CRUD operations using Mongoose in an Express.js application. We've seen how to define a Mongoose schema and model, and how to create, read, update, and delete documents in MongoDB.
Remember to test your work and understand each operation. Happy Coding!