Not being a particularly strong Javascript guy, I'm having a bit of trouble trying to update a lot of Date
objects in Mongo.
It seems that $inc
has not yet been implemented for Date
objects. So, to try and bump a bunch of dates by a day, I called (something like) this script from bash via mongo myScript.js
:
conn = new Mongo();
db = conn.getDB('myDatabase');
var incrementDates = function() {
db.blah.find(myQuery).forEach(function(doc) {
db.blah.update(
{ _id : doc._id
, my_date : { $exists : true }
}
, { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }}
);
});
}
incrementDates();
The basic idea seems to work well enough in the mongoDB shell:
> var doc = db.blah.findOne(myQuery)
> doc.my_date
ISODate("1962-11-02T23:00:00Z")
> new Date(doc.my_date.getTime() + 86400000);
ISODate("1962-11-03T23:00:00Z")
But not so well in the script:
TypeError: doc.my_date has no properties
So I take it that I'm trying to call getTime
on a null
somewhere, even though the query in my update should only return documents where my_date
exists.
Any ideas as to what's happening here? More importantly: is there a better way to do this?