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:
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:
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:
const url = 'mongodb://localhost:27017';
Use the mongo.connect()
method to establish a connection to the MongoDB instance client:
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
console.error(err);
return;
}
//...
});
You can now select a database using the client.db()
method:
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:
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:
collection.insertOne({name: 'Roger'}, (err, result) => {
});
To add multiple items, use the insertMany()
method and pass an array as the first parameter:
collection.insertMany([{name: 'Togo'}, {name: 'Syd'}], (err, result) => {
});
Finding Documents
To retrieve all documents from a collection, use the find()
method:
collection.find().toArray((err, items) => {
console.log(items);
});
To filter the collection and retrieve specific documents, pass an object to the find()
method:
collection.find({name: 'Togo'}).toArray((err, items) => {
console.log(items);
});
If you know you will only retrieve one element, you can skip the toArray()
conversion of the cursor by using findOne()
:
collection.findOne({name: 'Togo'}, (err, item) => {
console.log(item);
});
Updating Documents
To update an existing document, use the updateOne()
method:
collection.updateOne({name: 'Togo'}, {'$set': {'name': 'Togo2'}}, (err, item) => {
console.log(item);
});
Deleting Documents
To delete a document, use the deleteOne()
method:
collection.deleteOne({name: 'Togo'}, (err, item) => {
console.log(item);
});
Closing the Connection
Once you are done with the operations, call the close()
method on the client object to close the connection:
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:
collection.findOne({name: 'Togo'}, (err, item) => {
console.log(item);
});
Can be written using promises:
collection.findOne({name: 'Togo'})
.then(item => {
console.log(item);
})
.catch(err => {
console.error(err);
});
Or with async/await:
const find = async () => {
try {
const item = await collection.findOne({name: 'Togo'});
console.log(item);
} catch(err) {
console.error(err);
}
};
find();
Tags: MongoDB, Node.js, npm, callback, promises, async/await