跳过时间戳中间件以获取Mongoose中的某些更新

时间:2022-05-05 02:34:15

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

我的应用程序使用Mongoose并具有使用timestamps选项的模式:

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 * (example) suggested to use Foo.collection as that allegedly accesses the native MongoDB driver. So I tried this:

因此,只要将更新写入集合,updatedAt属性就会更改为当前日期。但是现在我想添加一些不应更新updatedAt属性的更改。 *(示例)上的一些答案建议使用Foo.collection,因为据称它访问本机MongoDB驱动程序。所以我尝试了这个:

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

However, that changed the updatedAt property as well.

但是,这也改变了updatedAt属性。

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

那么如何在不更改updatedAt的情况下更新文档?

2 个解决方案

#1


4  

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!

此查询不会更新updatedAt字段。希望你还需要这个!

#2


0  

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.

我能得到的是你自动更新updated_at字段的dateTime。您必须在架构中传递updated_at的默认值,只需删除该默认字段即可。

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.

从updated_at中删除默认字段,您的架构将如下所示。

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

#1


4  

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!

此查询不会更新updatedAt字段。希望你还需要这个!

#2


0  

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.

我能得到的是你自动更新updated_at字段的dateTime。您必须在架构中传递updated_at的默认值,只需删除该默认字段即可。

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.

从updated_at中删除默认字段,您的架构将如下所示。

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