Skip timestamps middleware for certain updates in Mongoose

。_饼干妹妹 提交于 2019-12-10 02:38:25

问题


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

var fooSchema = new Schema({
    name: String,
}, {
    timestamps: true,
});
mongoose.model('Foo', fooSchema);

So whenever an update is written to the collection, the updatedAt property is changed to the current date. But now I would like to add some changes that should not update the updatedAt property. Some answers on Stackoverflow (example) suggested to use Foo.collection as that allegedly accesses the native MongoDB driver. So I tried this:

Foo.collection.update({ _id: someFooId }, { $set: { name: 'New Name' } });

However, that changed the updatedAt property as well.

So how can I update a document, without changing updatedAt?


回答1:


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

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

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




回答2:


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);


来源:https://stackoverflow.com/questions/38621790/skip-timestamps-middleware-for-certain-updates-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!