0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your suspicion was correct and actually very logical. I'm still new to this asynchronous/callback stuff. Thanks
I've been doing JavaScript async programming for almost a year now, and I still get bit by it on a regular basis. It's a slippery beast!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.