Converting a mongo stored date back into milliseconds since Unix epoch when loaded?

前端 未结 5 394
名媛妹妹
名媛妹妹 2020-12-15 21:09

I am using Mongoose & Node.js for my webserver.

As a part of one of my document schemas, I have a \'timestamp\' field. The line for it in the schema is:

相关标签:
5条回答
  • 2020-12-15 21:26

    You can add the numerical milliseconds version of timestamp as a virtual attribute on the schema:

    schema.virtual('timestamp_ms').get(function() {
      return this.timestamp.getTime();
    });
    

    Then you can enable the virtual field's inclusion in toObject calls on model instances via an option on your schema:

    var schema = new Schema({
      timestamp: Date
    }, {
      toObject: { getters: true }
    });
    
    0 讨论(0)
  • 2020-12-15 21:30

    This works fine for me

    db.eurusd.ticks.findOne({_id:ObjectId("518636777055000000000000")}).t.getTime()
    

    returns time in miliseconds, where returned document has structure

    {
     "_id" : ObjectId("518636777055000000000000"),
     "t" : ISODate("2013-05-05T10:37:43Z"), // date data type
     "ask" : "Joe",
     "bid" : 33
    }
    
    0 讨论(0)
  • 2020-12-15 21:30

    when you set mongoose type as "Date" , mongoose convert timestamp to UTC, because timestamp is a number, not a Date. then if you want to store timestamp, you should set mongoose type as "Number".

    myfield{
        type: Number,
        default: Date.now()
    }
    
    0 讨论(0)
  • 2020-12-15 21:36
    var schema = new Schema({
      timestamp: {type:Number, default: new Date().getTime()}
    });
    

    Hope this will solve your issue.

    0 讨论(0)
  • 2020-12-15 21:36

    As a best practice, I would say: keep your data the type it deserves.

    Anyway, if your client needs to treat with numbers, you can simply pass the date as milliseconds to the client, and still work with Date objects in Node.

    Just call timestamp.getTime() and ta-da, you have your unix timestamp ready for the client.

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