2

I have an empty array that I want to push items onto, inside a loop. Once outside the loop, the array losses all information

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false}, function(err, cursor) {
            cursor.each(function(err, item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); //array is empty
        });

        console.log(result); //array is empty
lazandrei19
  • 85
  • 1
  • 3
  • 7
  • 1
    What exactly is `cursor`? does it's `each` method work asynchronously? If not, then your explanation of what is happening doesn't make sense. I wouldn't expect `.each` to be asynchronous. – Kevin B Apr 30 '15 at 19:57
  • `each` must be asynchronous. Where does that method come from? You should specify what framework/library you are using. –  Apr 30 '15 at 19:59
  • Is this MongoDB stuff? –  Apr 30 '15 at 20:07
  • This is MingoDB and it says on their site that cursors has the each function. – lazandrei19 May 01 '15 at 18:08

2 Answers2

1

It looks like you are using Mongoskin, you can use the toArray method to convert the cursor to an Array, which seems to be what you want. Check this out:

http://www.hacksparrow.com/mongoskin-tutorial-with-examples.html

db.collection('stuff').find().toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
});

So your code would look like this:

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false})
        .toArray(function(err, cursor) {
            // cursor is now an array. forEach is sync.
            cursor.forEach(function(item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); // Should not be empty now
            // Add more code in here, if you want to do something with
            // the result array
        });
        // Still empty, because find is async.
        // Your code should go inside of the users.find call
        // and not here
        console.log(result);

This is something you'll be dealing with a lot with node. For async code, the rest of your code must go inside of the async calls. You can keep dealing with callbacks, or use Promises, for instance.

0

This could be because users.find and cursor.each functions may be asynchronous, so your second console.log is executed before the execution of cursor.each and your third console.log is executed before users.find

Manuel Bitto
  • 5,073
  • 6
  • 39
  • 47