【问题标题】:how to use data to update something with findOneAndUpdate()如何使用数据通过 findOneAndUpdate() 更新某些内容
【发布时间】:2021-11-12 16:16:24
【问题描述】:

我希望更新我的数据库中的某些内容,但我需要使用数据库中对象中的数据。

这是我想做的:

score.findOneAndUpdate({name: "global"}, {$set:{score: score+1}})

这是它在 DB 中的样子:

{
  name: "global"
  score: 1
}

所以我需要找到全局,并将分数加一并更新以获得

{
 name: "global"
 score: 2
}

我知道我可以先查找并存储数据,然后再进行更新,但是我怎样才能使用 findAndUpdate() 完成一次呢?

【问题讨论】:

    标签: javascript mongodb request find


    【解决方案1】:

    您可以改为使用$inc 运算符来增加score 字段:

    score.findOneAndUpdate({ name: "global" }, { $inc: { score: 1 } });
    

    【讨论】:

    • 谢谢!它真的帮助了我!
    • 很高兴听到。标记答案是否有助于解决您的问题。
    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2017-10-12
    • 2013-07-01
    相关资源
    最近更新 更多