Using MongoDB with Express - Part 2

Using MongoDB with Express - Part 2

Express + MongoDB for powerful backend service.

In the previous article, we covered how to set up express and initialize the routes. In this article, we will cover setting up MongoDB and doing some operations on MongoDB.

Setting up MongoDB:-

  1. Type npm install mongodb and this install mongodb for you as a part of nodejs client
  2. Now let us go to the official website of mongodb https://cloud.mongodb.com/ and follow these steps
    • Build your first cluster
    • Create your first DB user (remember the username you set and also the password for the account)
    • Add an IP address to your access list (Whitelist the IP address with 0.0.0.0/0)
    • Connect to the cluster
  3. Now for the code part there is some code that you need to add in the app.js file, check below for this
const assert = require('assert')
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb+srv://<username>:<password>@clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";

Fill the placeholder positions in the above code for username, password, clustername, test=> this can be the database you want to use!

Now that we want to have CRUD operations on the database there is a redundant code with some changes for every operation. Follow this code snippet-

We will work with test DB and inventory collection. So you can have more than one collections inside a DB.

MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  // do the operations here
  client.close();
});
  • For adding a document
MongoClient.connect(url, function(err, client) {
        assert.equal(null, err);
        const db = client.db("test");
        db.collection('inventory').insertOne({
            item: "canvas",
            qty: 100,
            tags: ["cotton"],
            size: { h: 28, w: 35.5, uom: "cm" }
        })
        .then(function(result){
            console.log(result);
        })
        client.close();
    });

We can have insert many also to insert more than one document at a time.

  • To view all the document
MongoClient.connect(url, function(err, client) {
        assert.equal(null, err);
        const db = client.db("test");
        var cursor = db.collection('inventory').find({});
        function iterateFunc(doc) {
            console.log(JSON.stringify(doc,null,1));
        }
        function errorFunc(error) {
            console.log(error);
        }
        cursor.forEach(iterateFunc,errorFunc);
        client.close();
    });
  • To delete any particular document
MongoClient.connect(url, function(err, client) {
        assert.equal(null, err);
        const db = client.db("test");
        var myquery = { item: 'canvas' };
        db.collection("inventory").remove(myquery, function(err, obj) {
            if (err) throw err;
            console.log(obj.result.n + " document(s) deleted");
          });
        client.close();
      });

In the above code, we delete the collection document with the item as the canvas.

  • To update any particular document
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  var myquery = { item: "canvas" };
  var newvalues = { $set: {qty: 150, size.h: 30 } };
  dbo.collection("inventory").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
  });
  client.close();
});

Similarly, we can do update many. You can check that out in the docs. Ok, now you can see how easy it is to use Mongodb with Express and make a power-packed Backend service.

Ok, so this was the 2nd and last article for this small series. Follow me for more such articles in the future.