mongoose pre-aggregated reports

Problem

Following official mongodb docs ( http://docs.mongodb.org/manual/use-cases/pre-aggregated-reports/#log-an-event ) i'm trying to setup the same in nodejs + mongoose but there is a problem that i cannot figure out.

Problem is in $inc key : value, i cannot compute dynamic key like its already done in python:

 update = { '$inc': {
            'hourly.%d' % (hour,): 1,
            'minute.%d.%d' % (hour,minute): 1 } 
 }

My code looks like :

var daily_schema = mongoose.Schema({
    _id: 'string',
    metadata: {
        date: { type: 'date', default: Date.now() },
        site: 'string',
        page: 'string'
    },
    hourly: 'object',
    minute: 'object'    
});

var daily_stats = mdb.model('hits', daily_schema);

var date = new Date();
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var year = date.getFullYear();

daily_stats.update({
    _id : year + '/' + data.xid + '/' + data.url,
    metadata : {
        date : date,
        site : data.xid,
        page : data.url
    }
    },
    {
    $inc: { 
        'hourly.' + hour : 1, // (python: 'hourly.%d' % (hour,): 1,) how about javascript?
        'minute.' + hour + '.' + minute : 1
    }
    },
    { upsert: true }, function(err) {
        if (err) { console.log("daily_stats:upsert:error"); console.log(err) } else {
        console.log("daily_stats:upsert:ok");
    }           
    }
);

Please give me a hint how this can be done in javascript?

Best regards & thanks to all!

Problem courtesy of: innowww

Solution

You need to first build up your $inc object programmatically and then include that in your update call.

var inc = { $inc: {} };
inc.$inc['hourly.' + hour] = 1;
inc.$inc['minute.' + hour + '.' + minute] = 1;

daily_stats.update({
    _id : year + '/' + data.xid + '/' + data.url,
    metadata : {
        date : date,
        site : data.xid,
        page : data.url
    }},
    inc,
    { upsert: true }, function(err) {
        if (err) { console.log("daily_stats:upsert:error"); console.log(err) } else {
        console.log("daily_stats:upsert:ok");
    }           
});
Solution courtesy of: JohnnyHK

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.