Getting start with Express.js and MongoDB

Last Updated: August 21, 2017

In this lesson I am going to explain you how to get started with Express.js and MongoDB

First we will see how we connect to the MongoDB and then we will study basic database operations like Create,Read,Update and Delete (CRUD)

We will see how to create new collection in “Test” database

const express = require('express')  
const app = express()  
const port = 3000
const MongoClient=require("mongodb")

var url = "mongodb://localhost:27017/test"

app.get('/', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
	  	if (err) throw err;
	  	console.log("Database created!");
	  	db.close();
	  });
	response.send('Hello from Express!')
})

app.listen(port, function () {
  console.log('Example app listening on port 3000!')
})

Code explanation

  • MongoClient.connect is used with connection url to the database. This will create new database if it is not exists and make a connection to it

Create new collection

We will see how to create “products” collection in MongoDB

const MongoClient=require("mongodb")
const express = require('express')  
const app = express()  
const port = 3000

let url = "mongodb://localhost:27017/test"
app.get('/', (request, response) => { 

	MongoClient.connect(url, function(err, db) {
		if (err) throw err;

		db.createCollection("products",function(err, res) {
			if (err) throw err;
			console.log("Collection created!");
			db.close();
		})
	});
	response.send('Hello from Express!')
})

app.listen(port, function () {
	console.log('Example app listening on port 3000!')
})

Code explanation

  • db.createCollection is the method we used to create new collection. You have the callback function like the above example

Insert Document

Now we will see how to insert document to collection (in MongoDB we call it document but in Mysql we call it record)

app.get('/insert', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
		if (err) throw err;
		var product={product_id:2, product_name:'Coca Cola'}
		db.collection("products").insertOne(product, function(err, res) {
			if (err) throw err;
			db.close();
		});
	})
	response.send('1 document inserted')
})

Code explanation

  • var product={product_id:2, product_name:'Coca Cola'} We create the objects which we want to insert
  • Then you can use the db.collection("products").insertOne to insert document to collection

Now you can try to add several documents to the “product” collection

Find Document

In MongoDB you have find and findOne method to find document in collection. We will see how we can use those methods

app.get('/find', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
		if (err) throw err;
		db.collection("products").find({}).toArray(function(err, result) {
			if (err) throw err;
			console.log(result);
			db.close();
		});
	})
	response.send('Document Found')
})

You can see the following output in terminal

[ { _id: 59982cca0c944faa65f0b8d9,
    product_id: 1,
    product_name: 'Coca Cola' },
  { _id: 5998598cf4eae6aad85b81db,
    product_id: 3,
    product_name: 'Sprite' } ]

Code explanation

  • we used db.collection("products").find to find all documents in the collection.
  • You will get array of objects as the result
  • First parameter of the find() is empty object {}
  • This find() is equal to the SELECT * in MYSQL
  • findOne method will return only the first result

Other important thing with find() is the query object.
You can create the query object according to your criteria

app.get('/find', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
		if (err) throw err;
		var query={product_name:'Coca Cola'}
		db.collection("products").find(query).toArray(function(err, result) {
			if (err) throw err;
			console.log(result);
			db.close();
		});
	})
	response.send('Document Found')
})

Terminal Output

[ { _id: 59982cca0c944faa65f0b8d9,
    product_id: 1,
    product_name: 'Coca Cola' } ]

Code explanation

  • You can define your query object like this var query={product_name:'Coca Cola'}.
  • If you need you can use Regular Expression var query = { product_name: /^C/ }. This will get you the products which product_name is started with letter C

Update Document

Now we are going to update the document. I want to update product_name:”Sprite” with product_name:”Fanta”

app.get('/update', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
		if (err) throw err;
		var query={product_name:'Sprite'}
		var newObject={product_id:3,product_name:'Fanta'}

		db.collection("products").updateOne(query,newObject,function(err, res) {
			if (err) throw err;
			
			db.close();
		});
	})
	response.send('Document Updated')
})

Code explanation

  • Line 4 : You can define the query object
  • Line 5 : You can define the new object with updated data
  • Line 7 : updateOne method will update all the fields of the document
  • If the query finds more than one record, only the first occurrence is updated
  • By default, all the fields in the document will be updated, remember to fill all the fields otherwise they will be updated with blank values
  • You can update only the selected field using $set operator var newObject = {$set: { product_name: "Fanta" } }; So this will not update other fields as blank

Delete Document

You can use deleteOne() method in node.js to delete document from MongoDB collection

app.get('/delete', (request, response) => { 
	MongoClient.connect(url, function(err, db) {
		if (err) throw err;
		
		var query={product_id:3}

		db.collection("products").deleteOne(query,function(err, res) {
			if (err) throw err;
			
			db.close();
		});
	})
	response.send('Document Deleted')
})

Code explanation

Line 5: You can define the query object defining which element to delete
Line 7: Passing the query object parameter to the deleteOne()
You can use the deleteMany() to delete multiple documents