Search code examples
javascriptnode.jsmongodbsails.jssails-mongo

Handling async database in nodejs


I'm new in node js. I'm using sails js as framework. I'm trying to use nested database query. Please check the added code.

My current mongo collection name is todostatus. Form it i grabbed the data . Then I tried to use a callback function to iterate the data and update each item inside the data from database. But I'm not getting all the data. Can anyone please give me lead?

Thanks in advance,

Nixon

 TodoStatus.find({todo_id : req.params.todo_id}).done(function(errs, responsible){
                                if(errs){
                                }
                                else{

                                    function grabUsersName(todoRes, callback){
                                        async.forEach(todoRes, function (item, callback2){

                                           User.findOne ({id : item.user_id}).done(function (errses, user) {
                                                if(errses)
                                                {
                                                    console.log(errses);
                                                }
                                                else
                                                {
                                                    item['name'] = user.name;
                                                }

                                            });
                                        }, function(eerr) {
                                            callback(todoRes);
                                        });
                                    }

                                    grabUsersName(responsible, function(resultsa){
                                        console.log(resultsa);

                                        return res.view({
                                            responsible: resultsa
                                        })
                                    })



                                }
                            })

Solution

  • I found the solution.

    The issue is in the function grabUserName(). I missed to use callback for the async.forEach. Check the functions code for more information

    function grabUsersName(todoRes, callback){
        async.forEach(todoRes, function (item, callback2){
              User.findOne ({id : item.user_id}).done(function (errses, user) {
                    if(errses){
                       console.log(errses);
                    }
                    else{
                       item['name'] = user.name;
                       callback2();
                    }
               })
        }, function(eerr) {
                   callback(todoRes);
       });
    }