How to Integrate MongoDB with Node.js

In this article, I’m going to share how to integarte MongoDB with Node.js. Let’s get started:

Table of Contents

  1. Create Project and Install MongoDB
  2. Connect to MongoDB
  3. Create Database and Collection
  4. Insert Document
  5. Retrieve Document
  6. Update Document
  7. Delete Document
  8. Use Promises
  9. Close Connection

Create Project and Install MongoDB

Let’s create a project and navigate to the project folder:

# create project
mkdir nodemongo
# go to folder
cd nodemongo

Then initialize the project:

npm init -y

Now install MongDB official package using this command:

npm install mongodb

Connect to MongoDB

In the root directory, create a file called index.js. Open the file and paste this code:

index.js
const mongo = require('mongodb').MongoClient // mongodb client
const url = 'mongodb://localhost:27017' // you can write remote url too

mongo.connect(url, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err, client) => {
  if (err) {
    console.error(err)
    return
  }

  // success: write your logic here
})

Create Database and Collection

We can easily create or connect to an existing database using client.db() method.

const db = client.db('mynotepaper')

Connect to create collection (table) using db.collection() method.

const collection = db.collection('books')

The index.js file looks like:

index.js
const mongo = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017'

mongo.connect(url, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err, client) => {
  if (err) {
    console.error(err)
    return
  }

  // create/connect db
  const db = client.db('mynotepaper')
  console.log("Database connected...!")

  // create/select collection
  const collectionBook = db.collection('books')

  // more logic
})

Run node index.js or node index command to create mynotepaper database and books colection.

Insert Document

To add an object, we need to use insertOne() method. Have a look at the structure:

collectionName.insertOne({Object}, (err, result) => {
//
})

Let’s add a book:

var document = {
  name: "Book 1",
  author: "Author 1"
}

collectionBook.insertOne(document, (err, result) => {
  console.log(result)
})

We are able to add many documents at one. The structure:

collectionName.insertMany([Array], (err, result) => {
//
})

An example:

var documents = [
  {
    name: "Book 3",
    author: "Author 3"
  },
  {
    name: "Book 4",
    author: "Author 4"
  }
]

collectionBook.insertMany(documents, (err, result) => {
  console.log(result)
})

Retrieve Document

Get all documents:

collectionBook.find().toArray((err, items) => {
  console.log(items)
})

Get a single document:

collectionBook.findOne({name: 'Book 1'}, (err, item) => {
  console.log(item)
})

Filter collection:

collectionBook.find({name: 'Book 1'}).toArray((err, items) => {
  console.log(items)
})

Update Document

Using updateOne() method, we’re able to update an existing document:

collectionBook.updateOne({name: 'Book 1'}, {'$set': {'name':'Book 5','author':'Author 5'}}, (err, item) => {
  console.log(item)
})

Delete Document

Use the deleteOne() method to delete a document:

collectionBook.deleteOne({name: 'Book 1'}, (err, item) => {
  console.log(item)
})

Use Promises

We’re able to use promises and async/await. To get a document, normal call is:

collectionBook.findOne({name: 'Book 2'}, (err, item) => {
  console.log(item)
})

We can call using promises:

collectionBook.findOne({name: 'Book 2'})
  .then(item => {
    console.log(item)
  })
  .catch(err => {
    console.error(err)
  })
})

Close Connection

After completing all operations we should close MongoDB client object.

client.close()
That’s all. Thanks for reading. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.