Mogoose findOneAndUpdate如何知道对象是否存在以及是否被修改 [英] Mogoose findOneAndUpdate how to know wether object exist and if modified

查看:55
本文介绍了Mogoose findOneAndUpdate如何知道对象是否存在以及是否被修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用猫鼬的findOneAndUpdate方法:

I am using findOneAndUpdate method of mongoose:

function update_one_record(Model, unique_constraint, new_updated_values){ 
    obj=Model.findOneAndUpdate(
        //Similarly we have findOneAndRemove
        unique_constraint, 
        {$set: new_updated_values},
        {upsert: true}, 
        function(err, raw){
            console.log(err, raw)
    })
    return obj
}

我想知道:

  1. 该对象是否存在
  2. 如果未修改对象,则错误是什么.

推荐答案

来自猫鼬 findOneAndUpdate文档:

Model.findOneAndUpdate([条件],[更新],[选项],[回调])

发出mongodb findAndModify更新命令.

Issues a mongodb findAndModify update command.

查找匹配的文档,并根据更新arg对其进行更新, 传递任何选项,并将找到的文档(如果有)返回给 打回来.如果传递了回调,查询将立即执行.

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed.

关于您的问题:

  1. 如果找到文档,它将作为参数传递给回调.您可以使用选项new: true返回修改后的文档,而不是原始文档(默认为true).
  2. 错误(如果有的话)也将传递给回调函数.
  1. If a document is found it will be passed to the callback as a parameter. You can use the option new: true to return the modified document rather than the original, which defaults to true.
  2. The errors, if any, will be passed to the callback function as well.

请注意,findOneAndUpdate不会触发以下任何一项:

It is important to note that findOneAndUpdate will NOT trigger any of the following:

  • 默认值
  • 设置者
  • 验证者
  • 中间件

这篇关于Mogoose findOneAndUpdate如何知道对象是否存在以及是否被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆