0

I have to mongodb collection. first i will call to coll1 and get ids.Then I want to call coll2 and search by ids and some other fields.

when I am calling to funtion it is returing undefined.

how I can wait untill i m not get result from funtion.

coll1 docs sample: {

"_id" : ObjectId(""), "container_id" : "56867887fdb391ff09d15e9", "item_state" : [ { "user_id" : 1, "username" : "x", "state" : "1" }, { "user_id" : 2, "username" : "y", "state" : "3" } ], "name" : "members test" } enter code here

function listMyWorkitems(user_id,callback) {
    var user_id=1;
    var workItemList = new Array();
    db.collection('containers').find({'start_date':{"$lt":new Date(2017,02,11)}}).toArray(function(err,docs){
    console.log("doc length");
    console.log(docs.length);
    for (var i = 0; i < docs.length; i++) {
            db.collection('work_items').find({"$and":[{'container_id':docs[i]._id.toString()},{'item_state':{"$elemMatch":{'user_id':user_id,'is_active':1,'state':{"$in":["1","2","3"]}}}}]}).toArray(function(err,workDocs){
            //console.log(workDocs);
            for (var i = 0; i < workDocs.length; i++) {
                    for (var j = 0; j < workDocs[i].item_state.length; j++) {
                        var doc=workDocs[i].item_state[j]
                         workItemList.push(workDocs[i].name)
                    }
                }
            });
        }
          callback(workItemList);
});
}

listMyWorkitems(user_id,funtion(err,workItemList) {
console.log(workItemList)
});

I understand async auto concept but still it is returning empty list here is code what i tried till now.. i done for collection 1 but once it is solve then i can query to collection 2 also..

var async = require('async');
var mongojs = require("mongojs");
var db = mongojs("localhost/mc_dev");
    async.auto({
           coll1task: function(callback) {
            var idlist =[];
            console.log("ids fetch from collection 1");
            db.collection('containers').find({'start_date':{"$lt":new Date(2017,02,11)}}).toArray(function(err,docs){
             docs.forEach(function(doc){
             console.log(doc._id);
             idlist.push(doc._id);
            });});
            callback(null,idlist);
           },

       finalcontrol: [
          'coll1task',
          function(results,callback) {
            console.log(results.coll1task);
          }
       ],
},
   function(error, results) {
        console.log('error = ', error)
        console.log('results = ', results)         
    })

1 Answer 1

2

The best approach to do things asynchronously in node.js is by using modules like ASYNC or PROMISE.

You can visit async and get access to all the modules provided by this library.

Main modules provided by async library are

  1. async.series=> this is what you can use in your case. 2.async.parallel
  2. async.auto => I will suggest you to use this as it provide you to perform operations asynchronously as well as synchronously

Further more you can also use PROMISES as now they are the part of ECMA SCRIPT 6 there are various modules also which you can use to get this done.

Sign up to request clarification or add additional context in comments.

9 Comments

thanks for quick reply. I am new to node js.I got what you want to say.. But how i will use auto in my code.. can You please help me in code.how my code will be after using auto??
there are few more problems in your code. You must study closers in javascript where you will learn how to implement for loop in javascript. Then your callback should be at last when your loop gets over like {j==workDocs[i].item_state.length-1}. Just take two functions in your auto one where you will run your 1st query then 2nd where your can use the result of 1st and do the further steps.
yes i have to put callback outside of collection 1 query.. I can create 2 function in auto ,first will query coll1 whose output will go to function2 which will query collection2. But how we can call auto itself as funtion.. see in my this example.
'function x(callback){ async.auto({ task1: function(callback){ console.log("task1 called"); callback(null); }, task2: function(callback) { console.log("task2 called"); callback(null); }, finalTask: ['task1', 'task2', function(callback, results) { //Here the followings are the same: results.initialTask[1], results.task1[0], results.task2[0], results.task3[0] return 1; }] }); } x(function(e,d){ console.log("x funtion called"); console.log(d); });'
you can visit coderwall.com/p/rkbavg/playing-with-async-auto for more reference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.