Published Nov 24 2018
Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! โจ
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. 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.
You require the mongodb
package and you get the MongoClient object from it.
const mongo = require('mongodb').MongoClient
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'
Then use the mongo.connect()
method to get the reference to the MongoDB instance client:
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
console.error(err)
return
}
//...
})
Now you can select a database using the client.db()
method:
const db = client.db('kennel')
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')
Add to app.js the following function which uses the insertOne()
method to add an object dogs
collection.
collection.insertOne({name: 'Roger'}, (err, result) => {
})
You can add multiple items using insertMany()
, passing an array as the first parameter:
collection.insertMany([{name: 'Togo'}, {name: 'Syd'}], (err, result) => {
})
Use the find()
method on the collection to get all the documents added to the collection:
collection.find().toArray((err, items) => {
console.log(items)
})
Pass an object to the find()
method to filter the collection based on what you need to retrieve:
collection.find({name: 'Togo'}).toArray((err, items) => {
console.log(items)
})
If you know you are going to get one element, you can skip the toArray()
conversion of the cursor by calling findOne()
:
collection.findOne({name: 'Togo'}, (err, item) => {
console.log(item)
})
Use the updateOne()
method to update a document:
collection.updateOne({name: 'Togo'}, {'$set': {'name': 'Togo2'}}, (err, item) => {
console.log(item)
})
Use the deleteOne()
method to delete a document:
collection.deleteOne({name: 'Togo'}, (err, item) => {
console.log(item)
})
Once you are done with the operations you can call the close()
method on the client object:
client.close()
I posted all those examples using the callback syntax. This API supports promises (and async/await) as well.
For example this
collection.findOne({name: 'Togo'}, (err, item) => {
console.log(item)
})
Can be used with promises:
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'})
} catch(err => {
console.error(err)
})
}
find()