Mongoose: Store createdAt and updateAt as Unix timestamps?

Created on 8 Mar 2016  路  14Comments  路  Source: Automattic/mongoose

Hello.
I want to propose this feature. I've read docs and wasn't able to find how to do this. At my company, we store all dates as unix timestamps, which is very useful.

What do you think? I cat implement this and open a pull request.

I think we can extend timestamps to:

var thingSchema = new Schema(
  {..},
  {
    timestamps: {
      createdAt: 'created_at',
      fieldType: Number,
      dateFunc: function () {
        return Math.round(new Date().getTime()/1000); /* timestamp in seconds */
      }
    }
  }
);

where:
fieldType - type of the timestamps' fields
dateFunc - custom function to create date (we store dates in seconds, but new Date().getTime() returns milliseconds)

All 14 comments

Might be easier to implement this as a plugin. Getting it into core mongoose while still being backwards-compatible with the current timestamps implementation will be a pain, but plugins make this super easy :)

FWIW, mongodb internally stores dates as a unix timestamp, just the mongodb driver converts them into JavaScript dates.

@vkarpov15 Awesome! Thanks.

@leemalmac , I recommend using of JSON date instead of epoch date. Because MongoDB doesn't use epoch time. For more comfort development cycle you might use JSON date as timestamp.

@vkarpov15 , please correct, if I'm wrong..

Also I guess this issue should be closed.

What does it mean - MongoDB doesn't use epoch time? Epoch time is just a simple integer or I missed something?

You're right. But there is no any MongoDB function to do something on documents.

For example when making an aggregation and if an epoch date is wanted to evaluate, firstly it must be convert an ISODate.

This is just a suggestion from me.

Got it. This is a reasonable notice, thanks!

Yeah either way I'm going to close this for now, there's no real reason to use numeric timestamps.

When a JSON document with Date object is serialized, typically via JSON.stringify (e.g. using socket.io to frontend), the value will be converted to string object as JSON does not support date object (see https://www.w3schools.com/js/js_json_datatypes.asp). This will be 'lossy' as the string object resolution is in seconds. This makes data handling more cumbersome.

@deskoh that's a good point. Will re-open this.

So any way to add unix timestamps?

@SwapnilSoni1999 not currently.

@vkarpov15 looking forward tho

;_; you guys working on it right?

@SwapnilSoni1999 yep it is released in 5.9.0, see timestamps docs for an example.

Was this page helpful?
0 / 5 - 0 ratings