node.js - Using nodejs : mongodb find then add to Array -


i made simple db few users in mongodb , nodejs. next im looping through list , display users in list's names etc sys.puts().

no adding users array() this:

db.open(function(err, 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':user.name, 'email': user.email };                     sys.puts(">> adding user list... "+ user.name);                  }             });             db.close();         });     }); }); 

is how add users array? because users.lenght = 0. im bit lost now

what doing setting properties on array object, might bit confusing.

[] both used indexes , keys, means in case of array, users[0] return first element in array, users['blaid12'] get/set property blaid12' on array object, that's doingusers.blaid12`.

so in end array becomes more hashmap. length property not count properties of object, counts elements in array.

you have couple of ways of solving issue:

  1. use object {} , use user ids keys on object, you'll have keep track of user count via variable.

  2. use array array using users.push({'name':...}) append elements array, if need userid too, add object push array.

  3. go mixed approach, use array push values, , object map ids array indexes.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -