Blog

  • First of all to perform the CRUD operation we need to connect with mongodb,so to connect with mongodb we can use either mongodb driver or mongoose driver.So lets get started with using the mongoose driver.To connect with mongodb using express you need to do install express and mongodb in your project

    To install MongoDB and express you can use following commands:-

    npm install mongodb 

    npm install express

     var express=require('express');
    var app=express();
    var mongoose=require("mongoose")
    var db = mongoose.connection;
    var mongooseObj;
    db.on('error',console.error)
    db.once('open', function() {
        mongooseObj={db: db,
    
                users: db.collection('users')
                
    };
    console.log('okay we are connected to mongodb');
        mongoose.connect('mongodb://localhost/firstapp-dev');
    )};
     

    note :in case you doesnot have database with name firstapp-dev then mongoose will create the database with this name Now,we are all set to perform some CRUD operation with mongodb using the mongoose driver Retrieving values:  to retrieve value we have multiple opteion so firstly we are using the find() to retrieve the records from the collection of the data base:-

     mongooseObj.users.find().toArray(function(err,data){
            if(err)
            console.log(err);
            if(data)
            //perform the operation with data
        });
     

    The above code collection will return all the users of the collection. In case you want to retrieve some specific record from the collection then you can use following code:

     mongooseObj.users.findOne({username:"abhay"},function(err,data){
         if(err)
         console.log(err);
         if(data)
         //operation with data
         });
     

    Similarly ,when you want to retrieve the record using the id of the user then you must know that regarding to a particular user the database will generate a unique object id that is not in integer form so if you want to retrieve the record using the object id then you can get the record as:

      mongooseObj.users.findOne({_id: ObjectId("5513ba37651893a61ce343c0")},function(err,data){
         if(err)
         console.log(err);
         if(data)
         //operation with data
         })
     

    so we have many find() that are:-

    findById()

    findByIdAndUpdate()

     

    Inserting data: 

    we can insert a new record in our database by using insert() as :-

     mongooseObj.users.insert([{id:4},{name:"mayank"}],function(err,data){
            if(err)
                console.log(err);
            else
                //operation with the data
    
        })
     

    Updating data: 

    to update the record we can use update method as :-

      mongooseObj.students.update({studentId:1},{name:”abhay”}, function(err, result){
    //Handle success and failure
    });
     

    Deleting data: 

    we can delete a record by calling the remove() as:-

     mongooseObj.users.remove({username:"abhay"},function(err,data){
            if(err)
                console.log(err);
            if(data)
                console.log('record deleted')
        });
     

    So I hope it would help you in  playing with MongoDB,We will discuss more about MongoDB ,express and Node.js in future posts. 

    Thanks and Regards

    Mayank Tyagi

Tags: mongdb