MongooseError:查询已执行:Todo.updateOne({ _id: new ObjectId("612df063a8f

Md *_*zri 7 javascript mongoose mongodb node.js express

我将猫鼬更新到最新版本(6.0.2),现在我收到此错误并在.updateOne()执行时粉碎应用程序。但是数据库内部的对象更新。我的代码:

\n
async(req,res) => {\n    await Todo.updateOne(\n        {_id : req.params.id},\n        {\n            $set : {\n                status : "inactive"\n            }\n        },\n        (updateError) => {\n            // if updateError exist\n            if (updateError) {\n                // print error\n                printError(updateError);\n\n                // response the error\n                res.status(500).json({\n                    error : "There was a Server Side Error!"\n                });\n            } else {\n                // if error dose not exist\n                // print message\n                console.log("|===> \xef\xb8\x8f  Data Was Updated successfully! \xef\xb8\x8f <====|\\n");\n                // response success\n                res.json({\n                    message : "Todo Was Update successfully!"\n                });\n            }\n        });\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

Mig*_*dan 6

尝试将 .clone() 添加到 de updateOne 函数

\n
async(req,res) => {\n    await Todo.updateOne(\n         {_id : req.params.id},\n         {\n              $set : {\n                    status : "inactive"\n              }\n         },\n         (updateError) => {\n              // if updateError exist\n              if (updateError) {\n                    // print error\n                    printError(updateError);\n\n                    // response the error\n                    res.status(500).json({\n                         error : "There was a Server Side Error!"\n                    });\n              } else {\n                    // if error dose not exist\n                    // print message\n                    console.log("|===> \xef\xb8\x8f  Data Was Updated successfully! \xef\xb8\x8f <====|\\n");\n                    // response success\n                    res.json({\n                         message : "Todo Was Update successfully!"\n                    });\n              }\n         }).clone();\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

最新版本的猫鼬不重复执行

\n

https://mongoosejs.com/docs/migration_to_6.html#duplicate-query-execution

\n


Nen*_*vic 3

由于您使用的是async语法,因此请将代码放入try/catchblok 中:

async (req, res) => {
  try {
    await Todo.updateOne({ _id: req.params.id }, { $set: { status: "inactive"}});
    res.status(200).json({message: "Todo Was Update successfully!"});
  } catch (error) {
    res.status(500).json({error:'There was a Server Side Error!'})
  }
}

Run Code Online (Sandbox Code Playgroud)