F. Rakes
F. Rakes

Reputation: 1537

Array incrementing Javascript / node js / mongodb

I'm trying to gather data from a MongoDB with Node JS to draw a graph later.

My goal is to collect all entries by hour of the day. In my collection there is a "created_at" field which stores a Date Object.

I'm trying to store the data in an array with 24 slots like this:

// padding the array for each hour of the day
var hours = new Array(23);

// defaulting the value for each hour to 0
for(var i=0; i<hours.length; i++){
    hours[i] = 0;
}

db.collection.find({}, {"created_at": 1}, function(err, entry){
    if (err){ doSomething(); }
    else {
        entry.forEach(function(item, index){
                    // get hour of the day from the Date object
            h = item["created_at"].getHours();
            h = parseInt(h);
                    // store hour of the day and count it up
            hours[h]++;
            console.log("#%s: %s", index, h);
        });
    }
});

console.log(hours);

Now when I log hours I get the array with the default values. ie [0, 0, 0, 0 ... 0] I'm certain that the database has correct values as the console.log in the inner function gets correct data.

Upvotes: 0

Views: 205

Answers (1)

Ethan Brown
Ethan Brown

Reputation: 27282

I suspect the problem is one of concurrency: the collection's .find method is asynchronous. So your console.log after the call to .find gets executed before the entry.forEach ever even executes. Try moving the console.log into the body of the else clause, after the forEach (which is synchronous), and you should see the result you're looking for.

Going forward, you'll have to employ promises or something to get the results you want.

Upvotes: 2

Related Questions