在Sequelize中屏蔽updatedAt字段更新的问题求助
更新记录时禁用updatedAt字段无效的解决办法
我使用的Sequelize版本是^5.22.5,按照文档说明v5.9.2及以上版本支持禁用updatedAt字段的选项,但试了三种方法后,更新操作能正常执行,可数据库里的updatedAt字段还是会被修改:
已尝试的方法
方法1:调用模型的update方法并传入silent: true
model.update( { count: Number(model.count) + 2, }, { where: { id: 10 }, silent: true } );
方法2:调用模型的increment方法并传入silent: true
model.increment('count', { by: 2, where: { id: 10 }, silent: true });
方法3:调用save方法并传入silent: true
model.save ({ silent: true })
问题原因与解决办法
在Sequelize v5中,silent选项仅对实例方法生效,对模型的静态方法(比如直接调用Model.update()、Model.increment())不起作用,这就是之前尝试没效果的核心原因。具体解决方式如下:
- 使用实例的
update方法
先查询出目标记录的实例,再调用实例的update方法并设置silent: true:
const targetInstance = await model.findByPk(10); await targetInstance.update( { count: targetInstance.count + 2 }, { silent: true } );
- 使用实例的
increment方法
模型的静态increment不支持silent选项,改用实例的increment方法:
const targetInstance = await model.findByPk(10); await targetInstance.increment('count', { by: 2, silent: true });
- 使用实例的
save方法
确保调用的是实例的save方法而非模型的静态方法,先获取实例再操作:
const targetInstance = await model.findByPk(10); targetInstance.count += 2; await targetInstance.save({ silent: true });
另外需要注意:如果模型定义里手动设置了updatedAt: false,silent选项也不会产生预期效果,需确保模型中updatedAt是默认启用状态。
内容的提问来源于stack exchange,提问作者MGA
相关产品推荐
相关产品推荐

