Showing posts with label Mongoose. Show all posts
Showing posts with label Mongoose. Show all posts

Friday 7 July 2017

Mongoose iterate records over results using async module

Mongoose iterate records over results using callback functions

Download the async module in nodeJs Project?
npm install async --save



Inculude the module in NodeJS?
async= require('async');



Following are code snippet example which demostrate, how to update the listing?
app.get("get_chat_messages", function(req, res) {
    var vid = req.query.vid;
    
    //Get the records from mongoose
    AjaxChatMessage.find({vid: vid}, function(err, items) {

    //initalize vars
    var index
    var results={}

    //include the module
    async= require('async');

    //iterate records
   async.each(items,     
     function(item, callback){  
         index=items.indexOf(item);
         results[index]={};
         results[index].text=item.text;
         results[index].vid=item.vid;
         results[index].user_display_name=item.user_display_name;
         results[index].id=item.id;
         results[index].photo=item.user.photo;
         results[index].logintype=item.user.logintype;
         
       if((items.indexOf(item)+1)==items.length){
           res.send(results);
       }
     });
     
    }).sort({id: 1}).populate('user');
}



Wednesday 28 June 2017

What is a promise and how to use with mongoose?

What is a promise and how to use with mongoose?

Question: What is a promise?
A promise is an abstraction for asynchronous programming.
It's an object that proxies for the return value thrown by a function that has to do some asynchronous processing.


Question: How does promise work?
The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error)


Question: Give example of promise work in mongoose?
User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();
Here execute multiple function in one line is promise.


Question: How to setup mongoose with promise?
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/dbname');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("MongoDB connected Successfully.!");
});



Question: How to Add the data in mongoDb with mongoose?
//Ajax chat messages
var AjaxChatMessageSchema = mongoose.Schema({
    id: Number,
    userID: Number,
    userName: String,
    userRole: String,
    channel: String,
    dateTime: String,
    ip: String,
    text: String,
    status: String,
    vid: Number
}, {collection: 'ajax_chat_messages'});
var AjaxChatMessage = mongoose.model('ajax_chat_messages', AjaxChatMessageSchema);

var saveData={id:11, userName:'testuser',text:'hello user'}
var AjaxChatMessageDtls = new AjaxChatMessage(saveData);
AjaxChatMessageDtls.save(function(err) {
    if (err) {
        console.log("Error while saving the details");
        response.success = 0;
        res.send(response);
    } else {
        response.success = 1;        
        res.send(response);
    }
});



Question: How to do decrement the value by 1?
AjaxChatMessage.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();



Question: From where we can read more about promise?
http://mongoosejs.com/docs/promises.html


Thursday 8 June 2017

How to Create RESTful APIs in Node Js using Express JS and MongoDB

How to Create RESTful APIs in Node Js using Express JS and MongoDB

Question: What is RESTful APIs?
Full form of REST is Representational State Transfer. It is web standards architecture used to create an API.


Question: What type of request handled by RESTful APIs?
HTTP requests


Question: How to create an API?
  1. Create a folder with name of api in your node project, and  create three folder inside this. i.e controllers, models and routes.
  2. Create 3 empty files in each folder i.e todoListController.js, todoListModel.js and todoListRoutes.js
  3. Now, Folder Structure will be as below:
  4. -api
        --api/controllers/todoListController.js
        --api/models/todoListModel.js
        --api/routes/todoListRoutes.js
  5. Add Following script in each empty file: todoListController.js
    var mongoose = require('mongoose'),
            Task = mongoose.model('Tasks');
    
    /* List all todoList*/
    exports.list_all_tasks = function(req, res) {
        Task.find({}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    /* List all todoList*/
    exports.create_a_task = function(req, res) {
        var saveData = {}
        saveData.name = req.body.name;
        saveData.status = req.body.status;
        var new_task = new Task(saveData);
        new_task.save(function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });    
    };
    
    /* Get a todo list details*/
    exports.read_a_task = function(req, res) {
        Task.findById(req.params.taskId, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    /* UPdate a toto data*/
    exports.update_a_task = function(req, res) {
        Task.findOneAndUpdate(req.params.taskId, req.body, {new : true}, function(err, task) {
            if (err)
                res.send(err);
            res.json(task);
        });
    };
    
    
    exports.delete_a_task = function(req, res) {
        Task.remove({
            _id: req.params.taskId
        }, function(err, task) {
            if (err)
                res.send(err);
            res.json({message: 'Task successfully deleted'});
        });
    };


    todoListModel.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var TaskSchema = new Schema({
        name: {
            type: String,
            Required: 'Kindly enter the name of the task'
        },
        Created_date: {
            type: Date,
            default: Date.now
        },
        status: {
            type: [{
                    type: String,
                    enum: ['pending', 'ongoing', 'completed']
                }],
            default: ['ongoing']
        }
    });
    
    module.exports = mongoose.model('Tasks', TaskSchema);
    


    todoListRoutes.js
    module.exports = function(app) {
        var todoList = require('../controllers/todoListController');
    
    
        // todoList Routes
        app.route('/tasks')
                .get(todoList.list_all_tasks)
                .post(todoList.create_a_task);
    
    
        app.route('/tasks/:taskId')
                .get(todoList.read_a_task)
                .post(todoList.update_a_task)
                .delete(todoList.delete_a_task);
    }; 


  6. Create a myapp.js empty file in project folder and add following script code.
    var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModel'),
    bodyParser = require('body-parser');
    
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/Tododb');
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    var routes = require('./api/routes/todoListRoutes');
    routes(app);
    
    app.listen(port);
    console.log('RESTful API server started: ' + port+' PORT');
    
  7. Now you need install following modules
    npm install express
    npm install mongoose
    npm install body-parser
    
  8. Now run following command, to test the APIs
    node myapp.js
    



Question: Provide Create Task API
URL: http://localhost:3000/tasks
Method: POST
Request Data:
{
"name":"I need to go for walk",
"status":"ongoing"
}



Question: Provide List All records API
URL: http://localhost:3000/tasks
Method: POST
Response Data:
[{"_id":"5937ff6a5fc96f1c1492877f","name":"I will go for walk daily.","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:28:10.608Z"},{"_id":"593803fb5fc96f1c14928782","name":"Get up early in the morning","__v":0,"status":["ongoing"],"Created_date":"2017-06-07T13:47:39.246Z"}]



Question: Provide Update Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Request Data:
{  
  "name": "I goes on walk daily.", 
}



Question: Provide Get Records:
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: POST
Response Data:
{"_id":"5938d8e86d3e500cd8da6a12","name":"Arun kumar Gupta","__v":0,"status":["ongoing"],"Created_date":"2017-06-08T04:56:08.156Z"}



Question: Provide Delete Records
URL: http://localhost:3000/tasks/5938d8e86d3e500cd8da6a12
Method: DELETE
Response Data:
{
  "message": "Task successfully deleted"
}



Monday 5 June 2017

Mongoose Tutorial - listing records, Add Record, update record and delete record

mongoose tutorial - listing records, Add Record, update record  and delete record

Question: How to install the mongoose?
npm install mongoose



Question: How to update the mongoose?
npm update mongoose



Question: How to Start the mongoose?
Include the mongoose in the project
var mongoose = require('mongoose');

Make the Db connection with mongodb
mongoose.connect('mongodb://localhost:27017/test');
var db = mongoose.connection;

Check the Error OR Success on Db Connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
   console.log("MongoDB connected Successfully.!");
});  




Question: How to Create Model with mongoose?
Here we have set the two fields only, you can add more if required.
var TodoSchema = mongoose.Schema({
  id: String, //datatype is string
  name: String, //datatype is string          
});       
var Todo = mongoose.model('Todo', TodoSchema);

In mongoose.model, the first argument is the singular name of the collection.
Mongoose automatically looks for the plural version with lowercase of your model name.
means for Todo, it will look todos.



Question: How to set unique key for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});



Question: How to set unique key and required for a field?
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true }, 
  email: { type: String, unique: true, required:true }, 
  name: String, //datatype is string          
});



Question: How to list the records from mongodb?
var cursor = Todo.find({ }).cursor();
cursor.on('data', function(doc) {
    jsonData[doc.id] = doc.name;  
});
cursor.on('close', function() {
    console.log(jsonData);                   
});



Question: How to save the record?
var TodoDetails = new Todo({ id: "10",name:"this id test message"});
TodoDetails.save(function (err) {if (err) console.log ('Error on save!')});        



Question: How to update the record?
 Todo.update({id: "10" }, { $set: { name: "this is update message" }}, {}, function(){
             console.log("Update the records successfully");
        })



Question: How to delete the record?
    Todo.find({ id:"10" }).remove( function(){
     console.log("Record deleted successfully");
    }); 



Question: How to delete the document and check is it deleted?
Todo.find({ id:"10" }).remove( function(err, effectedRows){
    if(err){
         console.log("Unable to delete the record");
    }
    if(effectedRows.n==0){
        console.log("Zero Record deleted");
    }else{
        console.log("Record deleted successfully");
    }
     
 }); 



Question: What are the difference between mongoose.model and mongoose.Schema?
Model is an object that gives you easy access to a collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.

Schema is an object that defines the structure of the documents that will be stored.
it enables you to define types and validators for all data.



Question: How to get first record(s) from listing?
Todo.findOne({ 'name': 'kumar' }, 'id', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          

})        



Question: How to fetch specific column?
  Todo.find({ 'name': 'kumar' }, 'id name', function (err, person) {
          if (err) return handleError(err);
            //console.log(person);          
             res.send(person);
        })



Question: How to limit the number of records?
You can use limit method.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3);



Question: How to get listing by name in ascending order?
You can use sort method, -1 means descending order, 1 means ascending order.
Todo.find({}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: How to use "in" in where clause?
Todo.find({ name: { $in: ['arun', 'gupta']}, 'id name', function (err, person) {
  if (err) return handleError(err);
    console.log(person);          
     
}).limit(3).sort({ name: -1 });



Question: Give full Query example?
Todo.find({ 
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    name: { $in: ['technology', 'web'] }

}, 'id name', function (err, person) {
  if (err) return handleError(err);
    //Here will be display all the records
    console.log(person);               
}).limit(3).sort({ name: -1 });




Question: How to create custom function in mongoose.model?
In schema/Model file (Create a custom function)
var TodoSchema = mongoose.Schema({
  id: { type: Number, unique: true}, 
  name: String, //datatype is string          
});
TodoSchema.statics.findByIdTest = function (todoId,cb) {
  return this.model('Todo').find({ id: todoId }, cb);
};

How to use controller file.
Todo.findByIdTest(2677,function(error, data){
    console.log(data);    
});




Wednesday 22 March 2017

Express js Interview questions and answers

Express js Interview questions and answers

Question: How to install express js in node?
use following command to install express js.
npm install express



Question: How to use express js in node?
use require to include express module.
var app = require('express')();



Question: How to use handle get request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage"); //Shown in console
   res.send('This is GET Method for Homepage'); //Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle post request in express Js?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

app.post('/user_list', function (req, res) {
   console.log("Got a POST request for the user_list URL"); //Shown in console
   res.send('This is POST Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET/POST request for same URL expressJs?
/*Include require module*/
var app = require('express')();
var http = require('http').Server(app);

//This is POST Request
app.post('/add_user', function (req, res) {
   console.log("Got a POST request for the add_user URL"); //Shown in console
   res.send('This is POST Method for add_user URL');//Display as response
})

//This is Get Request
app.get('/user_list', function (req, res) {
   console.log("Got a GET request for the user_list URL"); //Shown in console
   res.send('This is GET Method for user_list URL');//Display as response
})

/*Start listing 8080 port*/
http.listen('8080', function() {
    console.log('listening on *:8080');
});



Question: How to use handle GET request for all URL start with ab* ?
app.get('/ab*', function(req, res) {   
   console.log("Got a GET request for /ab*");
   res.send('Page Regex Match');
})
Question: How to send Server call in Node?
Install the "request" module with following command.
npm install request

Include the request module in page, and send the request to server.
request = require('request');
request( "http://exmaple.com:8081:/users/add/?n=test&p=2277585&email=test@gmail.com", function(err, res, body) {                    
          console.log(res);
          console.log(body);
      });




Question: How to post data and get in express Js?
HTML Code

<form action="http://example.com:8081/register" method="GET">
Name: <input name="name" type="text" />  <br />
Email: <input name="email" type="text" />
         Phone: <input name="phone" type="text" />
         <input type="submit" value="Submit" />
      </form>


Express JS Code
app.get('/register', function (req, res) {   
   response = {
      name:req.query.name,
      email:req.query.email
      phone:req.query.phone
   };
   console.log(response);
   res.end(JSON.stringify(response));
})



Question: How to get cookie in Express js?
Install the "cookie-parser" module with following command.
npm install cookie-parser

Include the cookie-parser, in node.
app.get('/', function(req, res) {
   console.log("Cookies: ", req.cookies)
})


Question: How Static Files works in Express js?
Static files are images/videos/css/js etc.
For this, first you need to set the folder path using "express.static" method. See Example
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
   res.send('Hello ');
});
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
})



Question: How to upload images in Express js?
HTML Code

<form action="http://example.com:8081/file_upload" enctype="multipart/form-data" method="POST">
<input name="file" size="50" type="file" />         
         <input type="submit" value="Submit" />
      </form>

ExpressJS Code
var fs = require("fs");
var express = require('express');
var app = express();
var fs = require("fs");

app.post('/file_upload', function (req, res) {
   console.log(req.files.file.name);   
   var destinationFile = __dirname + "/images/" + req.files.file.name;
   
   fs.readFile( req.files.file.path, function (err, data) {
      fs.writeFile(destinationFile, data, function (err) {
         if( err ){
            console.log( err );
            }else{
               response = {
                  message:'File uploaded successfully in '+destinationFile,
                  filename:req.files.file.name
               };
            }
         //console.log( response );
         res.end( JSON.stringify( response ) );
      });
   });
})



Question: What are different methods in REST API?
  1. GET : Used to read.
  2. POST: Used to update.
  3. PUT: Used to create.
  4. DELETE: Used to delete



Question: How to setup the images and access them?
Add Following code in my server.js (OR main file).
app.use(express.static('public'))
Now, you can add images in public folder and can access like below:
http://localhost:3000/1.jpg
http://localhost:3000/2.jpg
http://localhost:3000/3.jpg



Question: How to do increment the value by 1?
 User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();



Question: How to do decrement the value by 1?
 User.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();