How to Use Mongodb With Nodejs

Posted By : Damini Sharma | 25-Nov-2018

Introduction

Mongodb is a database, responsible for storing and retrieving information. MongoDB is a NoSQL database. In NoSQL all databases do not use the SQL language for querying the data.

 

Prerequisite

We’ll be using the official mongodb npm package. If you already have a Node.js project you are working on, just install it:-

npm install mongodb

If you are starting from scratch, then create a new folder with your terminal and run npm init to start up a new Node.js project, and then run npm install mongodb command.

 

CONNECTING TO MONGODB

We need to require the mongodb package and get the access to MongoClient object from it.

Now, Create a URL to the MongoDB server. If you use MongoDB locally, the default URL will be something like mongodb://localhost:27017.

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.db() method:-

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 insertOne() method to add an object cats collection.

collection.insertOne({name: 'Meowsalot'}, (err, result) => {

})

We can add multiple items using insertMany() method, passing an array as the first parameter:-

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 need to be retrieved:

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, istead use findOne():

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 deleteOne() method to delete a document:

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()

 

 

Conslusion

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 MongoDB you'll be able to store any object while not having to stress regarding the actual fields that compose this object and the way to store them. you just tell MongoDB to store that object.

Data is stored in a format almost like JSON, but enhanced to allow storing more than just basic data types.

 

 

Request for Proposal

Name is required

Comment is required

Sending message..