How to Use Mongodb With Nodejs
Posted By : Damini Sharma | 25-Nov-2018
Introduction
Prerequisite
We’ll be using the official
npm install mongodb
If you are starting from scratch, then create a new folder with your terminal and run
CONNECTING TO
We need to require the
Now, Create a URL to the MongoDB server. If you use MongoDB locally, the default URL will be something like
const url = 'mongodb://localhost:27017'
Then, use the mongo.connect() method to get the reference of the MongoDB Database instance:-
mongo.connect(url, (error, client) => {
if (error) {
console.error(error)
return
}
//...
})
Now we can select a database using the client.
const db = client.db('kennel')
CREATE AND GET A COLLECTION
We can get a collection by using the db.collection() method. If the collection does not exist yet, it will be created for us.
const collection = db.collection('cats')
INSERT DATA INTO A COLLECTION A DOCUMENT
Add to app.js the following function which uses the
collection.insertOne({name: 'Meowsalot'}, (err, result) => {
})
We can add multiple items using
collection.insertMany([{name: 'Tigger'}, {name: 'Oscar'}], (err, result) => {
})
FIND ALL DOCUMENTS
Use the find() method on the collection to get all the documents inside a collection:-
collection.find().toArray((err, items) => {
console.log(items)
})
FIND A SPECIFIC DOCUMENT
Pass an object to the find() method to filter the collection based on what
collection.find({name: 'Tigger'}).toArray((err, items) => {
console.log(items)
})
If you know you are going to get one element, the toArray() method can be skipped,
collection.findOne({name: 'Tigger'}, (err, item) => {
console.log(item)
})
UPDATE AN EXISTING DOCUMENT
Use the updateOne() method to update a document:
collection.updateOne({name: 'Tigger'}, {'$set': {'name': 'Tigress'}}, (err, item) => {
console.log(item)
})
DELETE A DOCUMENT
Use the
collection.deleteOne({name: 'Tigger'}, (err, item) => {
console.log(item)
})
CLOSING THE CONNECTION
Once you are done with the operations you may close the connention instance:-
client.close()
USE PROMISES OR ASYNC/AWAIT
This API supports promises (and async/await) as well.
Following Code:
collection.findOne({name: 'Tigger'}, (err, item) => {
console.log(item)
})
Can be rewritten using promise as:
collection.findOne({name: 'Tigger'})
.then(item => {
console.log(item)
})
.catch(err => {
console.error(err)
})
or with async/await:
const find = async () => {
try {
const item = await collection.findOne({name: 'Tigger'})
} catch(err => {
console.error(err)
})
}
find()
MongoDB is a very JavaScript-friendly database. It exposes a JavaScript API which is used to create databases and collections of objects (called documents).
It is schemaless, which means you don’t need to pre-define a structure for the data before storing it.
In
Data is stored in a format almost like
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Damini Sharma
Damini is a young enthusiastic web designer who loves to explore latest, cutting edge tools and technologies in web development.