How to use MongoDB with Node.js
By Flavio Copes
Learn how to use MongoDB with Node.js: connect with MongoClient, then insert, find, update, and delete documents using the official mongodb npm package.
If you are unfamiliar with MongoDB check our guide on its basics and on how to install and use it :)
We’ll be using the official mongodb npm package (examples checked against mongodb@7.6.0). If you already have a Node.js project you are working on, install it using
npm install mongodb
If you start from scratch, create a new folder with your terminal and run npm init -y to start up a new Node.js project, and then run the npm install mongodb command.
Connecting to MongoDB
Import MongoClient from the mongodb package:
const { MongoClient } = require('mongodb')
Create a URL to the MongoDB server. If you use MongoDB locally, the URL will be something like mongodb://localhost:27017, as 27017 is the default port.
const url = 'mongodb://localhost:27017'
Create a client, then await connect(). You don’t need the old useNewUrlParser / useUnifiedTopology options any more:
const client = new MongoClient(url)
async function main() {
try {
await client.connect()
//...
} finally {
await client.close()
}
}
main()
Now you can select a database using the client.db() method:
const db = client.db('kennel')
Create and get a collection
You can get a collection by using the db.collection() method. If the collection does not exist yet, it’s created.
const collection = db.collection('dogs')
Insert data into a collection a Document
Add to app.js the following which uses the insertOne() method to add an object to the dogs collection:
const result = await collection.insertOne({ name: 'Roger' })
console.log(result.insertedId)
You can add multiple items using insertMany(), passing an array as the first parameter:
const result = await collection.insertMany([
{ name: 'Togo' },
{ name: 'Syd' },
])
console.log(result.insertedCount)
Find all documents
Use the find() method on the collection to get all the documents added to the collection. find() returns a cursor, so call toArray():
const items = await collection.find().toArray()
console.log(items)
Find a specific document
Pass an object to the find() method to filter the collection based on what you need to retrieve:
const items = await collection.find({ name: 'Togo' }).toArray()
console.log(items)
If you know you are going to get one element, use findOne():
const item = await collection.findOne({ name: 'Togo' })
console.log(item)
Update an existing document
Use the updateOne() method to update a document:
const result = await collection.updateOne(
{ name: 'Togo' },
{ $set: { name: 'Togo2' } }
)
console.log(result.modifiedCount)
Delete a document
Use the deleteOne() method to delete a document:
const result = await collection.deleteOne({ name: 'Togo' })
console.log(result.deletedCount)
Closing the connection
Once you are done with the operations you can call the close() method on the client object:
await client.close()
In a long-running server you usually keep one MongoClient for the process lifetime and close it on shutdown. In a short script, wrap the work in try / finally and close in finally.
Use promises or async/await
The driver API is promise-based. Prefer async/await. You can also chain promises if you prefer:
collection
.findOne({ name: 'Togo' })
.then((item) => {
console.log(item)
})
.catch((err) => {
console.error(err)
})
or async/await:
const find = async () => {
try {
const item = await collection.findOne({ name: 'Togo' })
console.log(item)
} catch (err) {
console.error(err)
}
}
find()Want me to talk about your product? You can sponsor this site.
Related posts about node: