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
- Create Project and Install MongoDB
- Connect to MongoDB
- Create Database and Collection
- Insert Document
- Retrieve Document
- Update Document
- Delete Document
- Use Promises
- 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:
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:
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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)