How to Use MongoDB with Node.js
In this tutorial, I will guide you on how to interact with a MongoDB database from Node.js.
Note: If you are unfamiliar with MongoDB, please check our guide on its basics and how to install and use it.
Prerequisites
Make sure you have the mongodb
npm package installed. If you already have a Node.js project, use the following command:
1 | npm install mongodb |
If you are starting from scratch, create a new folder in your terminal and run npm init -y
to start a new Node.js project. Then, run the npm install mongodb
command.
Connecting to MongoDB
Require the mongodb
package and get the MongoClient
object from it:
1 | const mongo = require('mongodb').MongoClient; |
Create a URL to connect to the MongoDB server. If you are using MongoDB locally, the URL will be something like mongodb://localhost:27017
, as 27017
is the default port:
1 | const url = 'mongodb://localhost:27017'; |
Use the mongo.connect()
method to establish a connection to the MongoDB instance client:
1 | mongo.connect(url, { |
You can now select a database using the client.db()
method:
1 | const db = client.db('kennel'); |
Creating and Getting a Collection
To get a collection, use the db.collection()
method. If the collection does not exist yet, it will be created:
1 | const collection = db.collection('dogs'); |
Inserting Data into a Collection (Document)
To add data to a collection, use the insertOne()
method to add an object to the dogs
collection:
1 | collection.insertOne({name: 'Roger'}, (err, result) => { |
To add multiple items, use the insertMany()
method and pass an array as the first parameter:
1 | collection.insertMany([{name: 'Togo'}, {name: 'Syd'}], (err, result) => { |
Finding Documents
To retrieve all documents from a collection, use the find()
method:
1 | collection.find().toArray((err, items) => { |
To filter the collection and retrieve specific documents, pass an object to the find()
method:
1 | collection.find({name: 'Togo'}).toArray((err, items) => { |
If you know you will only retrieve one element, you can skip the toArray()
conversion of the cursor by using findOne()
:
1 | collection.findOne({name: 'Togo'}, (err, item) => { |
Updating Documents
To update an existing document, use the updateOne()
method:
1 | collection.updateOne({name: 'Togo'}, {'$set': {'name': 'Togo2'}}, (err, item) => { |
Deleting Documents
To delete a document, use the deleteOne()
method:
1 | collection.deleteOne({name: 'Togo'}, (err, item) => { |
Closing the Connection
Once you are done with the operations, call the close()
method on the client object to close the connection:
1 | client.close(); |
Using Promises or Async/Await
Instead of using callback syntax, you can also use promises or async/await with this API.
For example, the following code:
1 | collection.findOne({name: 'Togo'}, (err, item) => { |
Can be written using promises:
1 | collection.findOne({name: 'Togo'}) |
Or with async/await:
1 | const find = async () => { |
Tags: MongoDB, Node.js, npm, callback, promises, async/await