gpt4 book ai didi

node.js - 防止 Mongoose findOneAndUpdate 中的 updatedAt 变化

转载 作者:IT老高 更新时间:2023-10-28 23:26:46 29 4
gpt4 key购买 nike

我更新了 Mongoose 模型,然后使用实现简单 View 计数器的 $inc 运算符检索:

const profile = await Profile.findOneAndUpdate({ userName }, { $inc: { viewsCount: 1 } });

Profile 架构启用了 timestamps 选项。问题是 updatedAtviewsCount 更新期间更新,这不是一个理想的行为。

我想在 viewsCount 更新时禁用 updatedAt 更新,最好通过尽可能少的查询。

我假设 Mongoose 时间戳是通过 pre-hook 实现的。

findOneAndUpdate 如何在不更新 updatedAt 的情况下增加 viewsCount

这可以通过否定时间戳钩子(Hook)的效果来实现吗?

有类似的问题可以解决 updatedAt 更新的问题,但解决方案不适合这种情况。

最佳答案

mongoose 5.9.3 开始,您可以将第三个参数设置为 { timestamps: false }

来自 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.

关于node.js - 防止 Mongoose findOneAndUpdate 中的 updatedAt 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54717199/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com