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
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.