[node.js] Which SchemaType in Mongoose is Best for Timestamp?

I'm using Mongoose, MongoDB, and Node.

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 DB. I would really appreciate it if someone could share a more efficient way of implementing this.

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

This question is related to node.js mongodb mongoose schema

The answer is


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


var ItemSchema = new Schema({
    name : { type: String }
});

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps

Docs: https://mongoosejs.com/docs/guide.html#timestamps


new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });


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

This means you need to update the date to "now" every time you save the object. Maybe you'll find this useful: Moongoose create-modified plugin


Mongoose now supports the timestamps in schema.

const item = new Schema(
  {
    id: {
      type: String,
      required: true,
    },
  { timestamps: true },
);

This will add the createdAt and updatedAt fields on each record create.

Timestamp interface has fields

  interface SchemaTimestampsConfig {
    createdAt?: boolean | string;
    updatedAt?: boolean | string;
    currentTime?: () => (Date | number);
  }

This would help us to choose which fields we want and overwrite the date format.


The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.


First : npm install mongoose-timestamp

Next: let Timestamps = require('mongoose-timestamp')

Next: let MySchema = new Schema

Next: MySchema.plugin(Timestamps)

Next : const Collection = mongoose.model('Collection',MySchema)

Then you can use the Collection.createdAt or Collection.updatedAt anywhere your want.

Created on: Date Of The Week Month Date Year 00:00:00 GMT

Time is in this format.


In case you want custom names for your createdAt and updatedAt

const mongoose = require('mongoose');  
const { Schema } = mongoose;

const schemaOptions = {
  timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
};

const mySchema = new Schema({ name: String }, schemaOptions);

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose

Examples related to schema

How to kill all active and inactive oracle sessions for user How to define object in array in Mongoose schema correctly with 2d geo index How to create a new schema/new user in Oracle Database 11g? What GRANT USAGE ON SCHEMA exactly do? Change Schema Name Of Table In SQL How can I export the schema of a database in PostgreSQL? Automated way to convert XML files to SQL database? SQL statement to get column type Difference Between Schema / Database in MySQL How to generate entire DDL of an Oracle schema (scriptable)?