Which SchemaType in Mongoose is Best for Timestamp?

后端 未结 6 1750
予麋鹿
予麋鹿 2020-12-07 16:08

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

相关标签:
6条回答
  • 2020-12-07 16:44
    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

    0 讨论(0)
  • 2020-12-07 16:50

    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);
    
    0 讨论(0)
  • 2020-12-07 16:57

    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

    0 讨论(0)
  • 2020-12-07 16:58

    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

    0 讨论(0)
  • 2020-12-07 16:59

    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.

    0 讨论(0)
  • 2020-12-07 17:02

    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.

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