/ #node js mongodb example #node js mongoose tutorial 

[Tutorial] Using mongodb with nodejs

Mongodb/node/mongoose

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling. MongoDB obviates the need for an Object Relational Mapping (ORM) to facilitate development.

MongoDB

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need

Nodejs

Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast and scalable network applications.

  • Using Mongoose we can connect MongoDB database and nodejs

Mongoose

It is the Mongodb framework which is used to connect nodejs with mongodb database.

1) To install mongoose in nodejs use npm package: sh npm install mongoose

2) Link mongoose with Nodejs server: sh var mongoose = require('mongoose');

3) To connect a new MongoDB database: sh mongoose.connect('mongodb://localhost/database_name');

  • Create Model for collection

    • Model - Models are used to create the fields of the documents.

    Example :

    var reg = mongoose.model('register',    //collection name
    {
        field1 : {type:String},         //string value
        field2 : {type:Number},         //number value
        field3 : {type: Object},            //json object value
        field4 : {type: Date},          //datetime value
        field5 : {type: Boolean},       //Boolean value true/false
        field6 : {type: String, required: true},    // string value must enter the value
        field7 : {type: Number, default: 0},    //number value    with default of '0' value
        field8 : {type: String, enum: ["active", "inactive","block"], default: "inactive"}, //string value which contain in enum array
        field9 : {type: Schema.Types.ObjectId, ref: 'modelName'}                       //object_id  of reference of another model
    });
    
  • To store the values into the mongodb server use the following syntax

    Syntax :

    objectname.save(function (err,data){
        //callback content
     });
    

    Example :

    var details = new reg(JSON_document);
    details.save(function (err,data) {    //insert to mongodb database
        if (err) {
            console.log('Error block');
        } else {
            console.log('Success block')
        }
    });
    
  • To Find data from the mongodb database use the following query i) To get only one data from database use below syntax or example

    Syntax :

    reg.findOne({},function(err,data){
        //callback content
    });
    

    Example :

    reg.findOne({key : value},function(err,data){
        res.send(data);     // send response 
    });
    

    ii) To get multiple data as array from database use below syntax or example

    Syntax :

    reg.find({},function(err,data){
        //callback content
    });
    

    Example :

    reg.find({key : value},function(err,data){
        res.send(data);     // send response 
    });
    

To Update data in mongodb database collection i) Normal update

Syntax :

reg.update(QUERY_VALUE, UPDATE_VALUE).exec(function(err,value){
    if(err){
        console.log("Error block")
    }else{
        console.log("Success block")
    }
});

Example :

reg.update({key:value}, {key1:value1,key2: value2}).exec(function(err,value){
    if(err){
        console.log("Error block")
    }else{
        console.log("Success block")
    }
});

ii) Find and update By default findOneAndUpdate returns the original document. If you want it to return the modified document pass an options object { new: true } to the function

Syntax :

reg.findOneAndUpdate({FIND_VALUE},{UPDATE_VALUE},{OPTIONAL}, 
   function(err, content){
    if(!err){
        res.json({status: "success", data: value});
    }else{
        res.json({status:"error"});
    }
});

Example :

reg.findOneAndUpdate({key: value}, 
    {key1: value1, key2: value2}, {new: true}, function(err, doc){
    if(err){
        console.log("Error block");
    }else{
        console.log("Success block");
    }
});

NOTE: if optional json contain {new:true} - it will return updated document details if optional json not contain or contain {new:false} - if will return old value

To delete a data collection from mongodb database:

i) Normal delete data from collection:

Syntax :

reg.remove(QUERY_VALUE);

Example :

reg.remove({key:value});

ii) Find and remove data from collection: Syntax :

reg.find({QUERY_VALUE}).remove().exec();

Example :

reg.find({key: value}).remove().exec();

iii) Drop collection from mongodb database: Syntax :

Collection_name.drop();

Example :

reg.drop();

For any query contact Clofus Innovations.