nicholaswmin
nicholaswmin

Reputation: 22949

How to save in MongoDB with timestamp and then retrieve results by week

I have this snippet right here which saves a user in my MongoDB:

router.post('/adduser', function(req, res) {
    var db = req.db;
    var document = req.body;
    var codeResponse = code();
    var timestamp = new Date();
    document.code = codeResponse;
    document.timestamp = timestamp;
    db.collection('userlist').insert(document, function(err, result){
        res.send(
            (err === null) ? { msg: '',code: codeResponse } : { msg: err }
        );
    }); });

As you can see it also generates a timestamp via the new Date(); function in JS.

How can retrieve users by week?

I tried this:

router.get('/winnerlist', function(req, res) {
    var db = req.db;
    var start = new Date(2014, 6, 14);
    var end = new Date(2014, 6, 29);
    db.collection('userlist').find({"timestamp": {"$gte": start, "$lt": end}}).toArray(function (err, items) {
        res.json(items);
    });
});

Upvotes: 1

Views: 1958

Answers (2)

nicholaswmin
nicholaswmin

Reputation: 22949

I am answering my own question.


I have done this when saving:

I just de-format the dates and save them as plain number such as

June-20-2014 becomes 20140620

router.post('/adduser', function(req, res) {
    var db = req.db;
    var document = req.body;
    var codeResponse = code();
    var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var timestamp = d.getFullYear() + 
    (month<10 ? '0' : '') + month + 
    (day<10 ? '0' : '') + day;
    document.code = codeResponse;
    document.timestamp = timestamp;
    db.collection('userlist').insert(document, function(err, result){
        res.send(
            (err === null) ? { msg: '',code: codeResponse } : { msg: err }
        );
    });
});

and then I use plain-old numbers without any formatting to range dates:

router.get('/winnerlist', function(req, res) {
    var db = req.db;
    var start = "20140621";
    var end = "20140623";
    db.collection('userlist').find({"timestamp": {"$gte": start, "$lt": end}}).toArray(function (err, items) {
        res.json(items);
    });
});

I will NOT mark this as accepted, maybe it's not the best solution yet.

Upvotes: 0

ozbey
ozbey

Reputation: 160

you can get the week number from the date object and after that you can insert the week number as a new property, i've found this useful method

Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

var today = new Date();

var week = today.getWeek();

console.log(week); //which will return 26 as today

Upvotes: 2

Related Questions