Using nodejs : mongodb find then add to Array

By : Harry

I made a simple db with a few users in it with mongodb and nodejs. Next im looping through the list and display the users in the list's names etc with sys.puts().

No I am adding the users to an Array() like this:, db) {
    db.collection('users', function(err, collection) {
        collection.find({}, {'sort':[['name', 1]]}, function(err, cursor) {
            cursor.each(function(err, user) {
                if(user != null) {
                    users[user._id] = { 'name', 'email': };
                    sys.puts(">> Adding user to list... "+;


Is this how I add the users to the array? Because the users.lenght = 0. Im a bit lost now

By : Harry


What you are doing is setting properties on the array object, that might be a bit confusing.

[] is both used for indexes and keys, that means in case of your array, users[0] will return the first element in the array, but users['blaid12'] will get/set the property blaid12' on the array object, that's like doingusers.blaid12`.

So in the end your array becomes more like a hashmap. The length property does not count the properties of the object, it counts the elements in the array.

You have a couple of ways of solving the issue:

  1. Use an object {} and use the user ids as keys on that object, you'll have to keep track of the user count via another variable.

  2. Use the array as an array by using users.push({'name':...}) to append elements to the array, if you need the userid too, then just add it to the object you push into the array.

  3. Go with a mixed approach, use an array to push the values, and then an object to map the ids to the array indexes.

This video can help you solving your question :)
By: admin