Crud with Node.js and MongoDB (part 2)

For the second part of building a CRUD with Node.js and MongoDB, we will add each operation of the CRUD operation to our project one by one and will look at each step in detail. If you have not gone through the first part of this tutorial you can visit CRUD with Node.js and MongoDB (part 1). And now we will be going into more detail in this tutorial and will be focusing on the CRUD operations.

Insert a record in MongoDB

The very first operation we are going to add is a simple insert. This insert functionality represents the C in CRUD. Type the following code in index.js

A simple insert code
const polka = require('polka');
const { MongoClient } = require("mongodb");

polka()
  .get('/create', (req, res) => {
	const client = new MongoClient("mongodb://localhost:27017");
	async function run() {
  	try {
    	await client.connect();
    	const database = client.db("intro");
    	const collection = database.collection("quotes");

    	const result = await collection.insertOne({"quote":"Life is what happens to you while you're busy making other plans."});
    	res.end(JSON.stringify(result));
  	} catch (e) {
    	console.log("Error: " + e);
  	} finally {
    	await client.close();
  	}
	}
	run().catch(console.dir);
  })
  .listen(3000, err => {
	if (err) throw err;
	console.log(`> Running on localhost:3000`);
  });

The code given above opens a connection to the MongoDB instance on your pc. Once done then a collection/table named intro and quotes are specified. 

After this, a document is inserted by the code, and results are sent back in an HTTP response. The output we will get once we restart the server is : 

Retrieve a document in MongoDB

Now in this part, we will be reading the document which is the R part in the CRUD. We will use .get() to retrieve the documents from MongoDB.

Code for retrieving a document
.get('/retrieve', (req, res) => {
	const client = new MongoClient("mongodb://localhost:27017");
	async function run() {

  	try {
    	await client.connect();
    	const database = client.db("intro");
    	const collection = database.collection("quotes");

    	const cursor = collection.find({}, {});

    	let items = [];
    	await cursor.forEach(function(doc){
      	items.push(doc);
    	});
    	res.end(JSON.stringify(items));
  	} catch (error){
    	console.warn("ERROR: " + error);
	    if (errCallback) errCallback(error);
  	} finally {
    	await client.close();
  	}
	}
	run().catch(console.dir);
  })

The above code first connects to MongoDB. THen a find command is issued with an empty query. An empty query suggests that it matches all the documents. After this, a response is taken and it is marshaled into an array so that it can be sent back to the client. The Cursor operations are Asynchronous as await keyword was used in collection.insertOne to handle these without nested callbacks.   

Restarting the server will help us test the new endpoint. The output is given below

Update a document in MongoDB

Now coming to the update part in the CRUD. Type the following code to update the collection.

Code for Updating a document
const polka = require('polka');
const { MongoClient } = require("mongodb");

polka()
  .get('/create', (req, res) => {
	const client = new MongoClient("mongodb://localhost:27017");
	async function run() {
  	try {
    	await client.connect();
    	const database = client.db("intro");
    	const collection = database.collection("quotes");

    	const result = await collection.insertOne({"quote":"Life is what happens to you while you're busy making other plans."});
    	res.end(JSON.stringify(result));
  	} catch (e) {
    	console.log("Error: " + e);
  	} finally {
    	await client.close();
  	}
	}
	run().catch(console.dir);
  })
  .listen(3000, err => {
	if (err) throw err;
	console.log(`> Running on localhost:3000`);
  });

Firstly this code connects to MongoDB and then it creates an updated document. $set field tells the MongoDb to make changes.

This code first connects to MongoDB and then creates an updated document. MongoDB gets all the changes code wants to make using the $set field. This contains an object with the fields and values to change. “John Lennon” was the author in our case.   

We are using updateOne() function in our code which when executed updates the doc. As we want to match the whole document so there will be no parameters and we will leave it blank. And in the end, it will send back the updated documents. The code will give out the following output. 

Delete a document in MongoDB

The final letter in the CRUD acronym is D for delete.

Rest Apis and operations 

In today’s world, we use HTTP methods like POST, DELETE, and PUT in real-world applications to map various comments. Also, you would follow REST conventions. For keeping it simple for you this tutorial used GET requests. The code given below is for deleting a document. Type it in your js file and run it. 

Code for Deleting a document
.get('/delete', (req, res) => {
	const client = new MongoClient("mongodb://localhost:27017");
	async function run() {
  	try {
    	await client.connect();
    	const database = client.db("intro");
    	const collection = database.collection("quotes");
    	const query = { };
    	const result = await collection.deleteOne(query);
    	if (result.deletedCount === 1) {
      	res.end("Successfully deleted one document.");
    	} else {
      	res.end("Deleted 0 documents.");
    	}
  	} finally {
    	await client.close();
  	}
	}

You will get the following output as the result of running the code above.

Again we used an empty query because we wanted to match all of the documents in the “quotes”. collection.deleteOne() function will return the affected documents. Use Ctrl+C to stop the server and then start the server again to see the changes.

The deletion of the document can be verified with

curl http://localhost:3000/retrieve.

This is it with today’s tutorial which was CRUD app with node and MongoDB Part 2. For more detailed learning on NodeJS and other technologies related to NodeJS, also you can visit our website’s home page. You can always find tutorials of your choice. Other than this, you can always visit the official website of NodeJS which is https://nodejs.org . This website contains in-depth documentation of NodeJS.

Scroll to Top