MongoDB + Node.js: unable to insert date properly


I′ve been using node-mongoskin to connect this two. Everything was ok until I queried some "date" field which I think should be returned as javascript′s Date object. But result′s type was string, which is odd (for me) and inconvenient.

Inserting looks something like this:

var doc = {
  date: new Date(),
  info: 'Some info'
db.users.insert( doc, {safe: true}, function(err, res) {

And result of above is (without _id field):

{ "date" : "Mon Oct 24 2011 18:00:57 GMT+0400 (MSK)", "info": "Some info" }

However, inserting with MongoDB Shell works just fine, except type of field is ISODate

> db.things.insert({ date: new Date() }); db.things.find();
{ "_id" : ObjectId("4eae9f2a34067b92db8deb40"), "date" : ISODate("2011-10-31T13:14:18.947Z") }

So, the question is: how should I insert documents to query date fields as Date object? What I want is setting fields on database-server-side. I just send something like null-fields, and db-server setting those for me using default mongo′s mechanisms.

Inserting timestamps (as native MongoDB timestamp) is also a problem, but it′s not such a big deal.

PS: No luck going through mongoskin and mongodb-native docs.

10/31/2011 1:26:56 PM

Accepted Answer

It was probably some bug in my code or the mongo driver. Now, the following works just fine:

db.collection.insert({d: new Date()});

Timestamps support described here:

11/6/2012 1:35:05 PM

JavaScript code:

    collection.insert({"className"     : "models.Action", 
                       "title"         : "Email",
                       "description"   : "How are you today?",
                       "creationDate"  :  new Date("Fry, 4 May 2012 10:30:08 +0200 (CEST)"),
                       "creator"       : dbref },

produced in mongoDB

> db.action.find({"title":"Email"})
{ "className" : "models.Action", "title" : "Email", "description" : "How are you today?", "creationDate" : ISODate("2012-05-04T08:30:08Z"), "creator" : { "$ref" : "person", "$id" : ObjectId("4f995e4824ac8d68f63adf69") }, "_id" : ObjectId("4fa79e2e92c2a19a09000002") }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow