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');
}



No comments :

Post a Comment