MongoDB + Node.js: unable to insert date properly

后端 未结 3 538
清歌不尽
清歌不尽 2021-01-12 03:25

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

相关标签:
3条回答
  • 2021-01-12 03:49

    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"})
    > 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") }
    
    0 讨论(0)
  • 2021-01-12 03:58

    ISODate is the native way for mongo to store date. I use node-mongodb-native npm module and I store/retrieve javascript Date using new Date() idiom like in your examples. I don't know if it's a recent correction because I started node and Mongo in 2012, but using date was pretty straightforward for me.

    0 讨论(0)
  • 2021-01-12 04:00

    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: http://mongodb.github.com/node-mongodb-native/api-bson-generated/timestamp.html.

    0 讨论(0)
提交回复
热议问题