Let us learn Node.js Part V- MongoDB

Mostly all modern day web applications have some sort of data storage system at the backend to store data. For example, if one takes the case of a web shopping application, data such as the price of an item or the number of items of a particular type would be stored in the database.

The Node js framework has the ability to work with databases which are commonly required by most modern day web applications. Node js can work with both relational (such as Oracle and MS SQL Server) and non-relational databases (such as MongoDB).

 

Installing the NPM Modules:

To access Mongo from within a Node application, a driver is required. There are number of Mongo drivers available, but MongoDB is among the most popular. To install the MongoDB module, run the below command

npm install mongodb

Creating a Database:

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.

 

Example:

File:index.js

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

 

Run the code in terminal: node index.js

Result: Database created!

Creating a Collection:

To create a collection in MongoDB, use the createCollection() method:

Example:

File:collection.js

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.createCollection("customers", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});

Run the code in terminal: node collection.js

Result: Collection created!

Insert Into Collection:

 

To insert a record, or document as it is called in MongoDB, into a collection, we use the insertOne() method.

The first parameter of the insertOne() method is an object containing the name(s) and value(s) of each field in the document you want to insert.

Example:

File:insert.js

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = { name: "Company Inc", address: "Highway 37" };
  dbo.collection("customers").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
});

Run the code in terminal: node insert.js

Result: 1 document inserted

Sources:

Add a Comment

Your email address will not be published. Required fields are marked *