Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • NodeJS and MongoDB

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 297
    Comment on it

    Node.js which make use of chrome v8 engine can be used for building fast, scalable network applications. It is based on event-driven and non-blocking I/O model thus making it lightweight and efficient and most suitable for real time application.

     

    MongoDB has rapidly grown to become a popular database for web applications and can be used effectively with Node.js so as to letting developer write entire application in javascript making use of Node.js and MongoDB.

     

    Below are the different data-type being supported by mongoDB :


        -> Float is a 8 byte
        -> Double class a special class representing a float value
        -> Integers
        -> Long class
        -> Date maps
        -> RegExp maps
        -> String maps
        -> Binary class
        -> Code class
        -> ObjectID class
        -> DbRef class
        -> Symbol class

     

    We are thinking over here that you already have Node.js installed so in order to integrate Node.js with MongoDB we will need to install a MongoDB module being provided for Node.js.

     

    npm install mongodb --save

     

    Once you have mongodb installed you can start integrating it with your node project.

     

    Create connection with mongoDB

     

    var MongoClient = require('mongodb').MongoClient
      , assert = require('assert');
    // Connection URL
    var db_url = 'mongodb://localhost:3000/my_project';
    // Use connect method to connect to the Server
    MongoClient.connect(db_url, function(err, db) {
      assert.equal(null, err);
      console.log("Connected to mongoDB");
      db.close();
    });

     

    MongoDB have a inbuilt method find which can be used to retrieve data from a particular collection . Beside this MongoDB also provide list of other functions which can be used accordingly.

     

    Inserting a Document

     

    var addDocuments = function(db, callback) {
      // Get the documents collection
      var collection = db.collection('documents');
      // Insert some documents
      collection.insertMany([
        {a : 1}, {a : 2}, {a : 3}
      ], function(err, result) {
        assert.equal(err, null);
        assert.equal(3, result.result.n);
        assert.equal(3, result.ops.length);
        console.log("Inserted 3 documents into the document collection");
        callback(result);
      });
    }

     

    Lets add addDocuments to MogoClient.connect :

     

    var MongoClient = require('mongodb').MongoClient
      , assert = require('assert');
     
    // Connection URL
    var url = 'mongodb://localhost:27017/myproject';
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, db) {
      assert.equal(null, err);
      console.log("Connected correctly to server");
     
      addDocuments(db, function() {
        db.close();
      });
    });

     

    Now if you will run the updated app.js file as

     

    node app.js

     

    You should see the following output after running the app.js file.

     

     -> Connected correctly to server
     -> Inserted 3 documents into the document collection

     

    Similarly we can have different functions performing remaining curd operations as required :

    Updating a document

     

    var updateDocument = function(db, callback) {
      // Get the documents collection
      var collection = db.collection('documents');
      // Update document where a is 2, set b equal to 1
      collection.updateOne({ a : 2 }
        , { $set: { b : 1 } }, function(err, result) {
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        console.log("Updated the document with the field a equal to 2");
        callback(result);
      });  
    }

     

    Delete a document

     

    var deleteDocument = function(db, callback) {
      // Get the documents collection
      var collection = db.collection('documents');
      // Insert some documents
      collection.deleteOne({ a : 3 }, function(err, result) {
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        console.log("Removed the document with the field a equal to 3");
        callback(result);
      });
    }

     

    Find All Documents

     

    var findDocuments = function(db, callback) {
      // Get the documents collection
      var collection = db.collection('documents');
      // Find some documents
      collection.find({}).toArray(function(err, docs) {
        assert.equal(err, null);
        assert.equal(2, docs.length);
        console.log("Found the following records");
        console.dir(docs);
        callback(docs);
      });
    }

     

    Thus we cover the basic CURD operations in this tutorail we will go in more detail regarding all the buildin functions or methods being provided by mongoDB.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: