So I started to learn server code and I think the most important part of a server application is its connection with the application's database .
So I started with an express app first and chose mongoDB as the database.
I saw that most of the tutorials were around a library called mongoose when you searched mongoDB . So I decided why not go through the methods that mongoDB provides for my CRUD operations . Hence I am writing this blog .
Basically I've made a Todo List app but used the mongoDB Node.js drivers and not mongoose . This helped me in learning how to code by going through the documentation and not just rely on a way what everyone is showing .
Although I do believe Mongoose has some benefits , but still If you want to make a simple application and store data on MongoDB you can easily avoid using Mongoose . I hope you like this blog ...
app.js
import express from "express";
import cors from 'cors'
import tasksRouter from "./routes/tasks.js";
import { MongoClient, ServerApiVersion } from "mongodb";
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api/v1/tasks", tasksRouter);
const uri =
"mongodb+srv://yash_sharma:######@cluster0.vsqei.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
let tasksCollection;
async function run() {
const connectDb = async () => {
try {
await client.connect();
const database = client.db('tasks-manager')
tasksCollection = database.collection('tasks')
console.log('connected to db')
app.listen(5050, () => console.log("server running on port 5050..."));
} catch (err) {
console.dir(err);
}
};
connectDb()
}
run()
export { client, tasksCollection }
Controllers
For reading the collection in mongoDB you can use find()
const getTasks = async (req, res, next) => {
const taskList = tasksCollection.find().limit(50)
const data = [];
await taskList.forEach((item) => data.push(item))
res.status(200).json({ msg: "success", data });
};
For creating a single document in your collection you can use insertOne()
const postTask = async (req, res, next) => {
const { task } = req.body;
if (task === "") {
return res.status(404).json({ msg: "Please give a valid task" });
}
const newTask = { task };
await tasksCollection.insertOne(newTask);
res.status(200).json({ msg: "Task added succesfully" });
};
For updating a document we can use updateOne() , just make sure you use $set for updated doc
const editTask = async (req, res, next) => {
const { id } = req.params;
const { task } = req.body;
const filter = { _id: ObjectId(id) };
const updateDocument = { $set: { task } };
const options = {};
const result = await tasksCollection.updateOne(
filter,
updateDocument,
options
);
res.status(200).json({ msg: "task updated succesfully" });
};
For deleting a document we can use deleteOne()
const deleteTask = async (req, res, next) => {
const { id } = req.params;
const query = { _id: ObjectId(id) };
const result = await tasksCollection.deleteOne(query);
if (result.deletedCount === 1) {
return res.status(200).json({ msg: "task deleted succesfully" });
} else {
return res.status(404).json({ msg: "Please give a valid task id" });
}
};
So that's how you can interact with MongoDB without using mongoose . You can also go through the documentation to explore more .
https://www.mongodb.com/docs/drivers/node/current/usage-examples/
Thank You ๐ for reading this blog . I hope this helps someone ๐ .