Skip timestamps middleware for certain updates in Mongoose

前端 未结 3 1667
北恋
北恋 2021-01-04 16:14

My application uses Mongoose and has a schema that uses the timestamps option:

var fooSchema = new Schema({
    name: String,
}, {
    timestamps: true,
});
         


        
相关标签:
3条回答
  • 2021-01-04 17:01

    From mongoose 5 onwards , there is timestamps option which can be passed in Model.updateOne() and model.update() to skip timestamps for this update.

    Directly from docs:

    [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

    For example given in the question , timestamp updates can be skipped like this ,

    Foo.updateOne({ __id: someFooId },{ $set: { name: updatedName } }, { timestamps: false });
    
    0 讨论(0)
  • 2021-01-04 17:02

    What i can get is you are automatically updating the dateTime of updated_at field. You must be passing a default value for the updated_at in your schema, just remove that default field.

    For example.

    var fooSchema = new Schema({
        name: String,
    }, {
        updated_at:{
             type: Date,
             default: Date.now
        }
    });
    mongoose.model('Foo', fooSchema);
    

    Remove the default field from updated_at and your schema will look like this.

    var fooSchema = new Schema({
        name: String,
    }, {
        updated_at: Date
    });
    mongoose.model('Foo', fooSchema);
    
    0 讨论(0)
  • 2021-01-04 17:06

    I just found a solution and it works perfectly to me.

    mongoose.connection.db.collection('player').updateOne(
        {_id: mongoose.Types.ObjectId('56cb91sf34746f14678934ba')},
        {$set: {name: 'Test'}}
    );
    

    This query will not update the updatedAt field. Hope you still need this!

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