Search code examples
node.jsmongodbmongooseschema

Which SchemaType in Mongoose is best for a timestamp?


I'm using Mongoose, MongoDB, and Node.js.

I would like to define a schema where one of its fields is a date\timestamp.

I would like to use this field in order to return all of the records that have been updated in the last 5 minutes.

Due to the fact that in Mongoose I can't use the Timestamp() method, I understand that my only option is to use the following JavaScript method:

time : { type: Number, default: (new Date()).getTime() }

It's probably not the most efficient way for querying a humongous database. Is there a more efficient way of implementing this.

Is there a way to implement this with Mongoose and be able to use a MongoDB timestamp?


Solution

  • Edit - 20 March 2016

    Mongoose now support timestamps for collections.

    Please consider the answer of @bobbyz below. Maybe this is what you are looking for.

    Original answer

    Mongoose supports a Date type (which is basically a timestamp):

    time : { type : Date, default: Date.now }
    

    With the above field definition, any time you save a document with an unset time field, Mongoose will fill in this field with the current time.

    Source: http://mongoosejs.com/docs/guide.html