Mongoose - CRUD Operations
January 25th 2021 77

Mongoose has a flexible API
and provides many ways to accomplish a task. We will not focus on the variations because that is out of scope for this article, but remember that most of the operations can be done in more than one way either syntactically or via the application architecture.
Create Record
Let’s create a todo and save into our database:
let newTask = {
description: "task added using create",
};
Tasks.create(newTask)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
Firstly we had created a newTask
object with description of a todo which is a mandatory field required to create a document in the database. Mongoose model has a create()
method which is a promise
and on successful we get the response in data and in-case of failure it is catched and error is displayed.
Find All Tasks
To get all the documents stored inside a collection.
//all tasks
Tasks.find({})
.then((data) => {
console.log("All tasks", data);
})
.catch((err) => {
console.log(err);
});
Find A Single Document or Record
Lets see how we can find a single
document from the collection.
//find with condition
Tasks.find({ completed: false })
.then((data) => {
console.log("All tasks", data);
})
.catch((err) => {
console.log(err);
});
Update a Document
Let’s modify the record by updating the status completed:false to completed:true
Tasks.findByIdAndUpdate({ _id: req.params.id },{
$set: {completed:true},
},
{ new: true, useFindAndModify: false } //get updated result
)
.then((data) => {
console.log("Updated todo data", data);
})
.catch((err) => {
console.log(err);
});
Delete a document from the collection
//delete all tasks
Tasks.remove({});
// delete specific task
Tasks.findByIdAndRemove(task_id)
.then((data) => {
console.log("All tasks", data);
})
.catch((err) => {
console.log(err);
});
In the above example replace the task_id
with the value of _id
of a task in mongoDB databse which looks like 5a78fe3e2f44ba8f85a2409a
So we have seen all the CRUD
operations namely, create
, read
, update
, delete
Lets use them in our app.js
file.
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config({ path: ".env" });
const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;
//model
const Tasks = require("./models/todos");
const connect = mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
(db) => {
console.log("Connected Successfully to Mongodb Server");
//all tasks
Tasks.find({})
.then((data) => {
console.log("All tasks", data);
})
.catch((err) => {
console.log(err);
});
// similary use all the other operation here
// CAUTION: don't put all the operation together, use one operation
// at a time
},
(err) => {
console.log(err);
}
);
const app = express();
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now, run your server by using following command
first install,
npm install -g nodemon
then,
nodemon app.js