使用Mongoose findOneAndUpdate时报Query was already executed错误如何解决
错误原因
你同时为findOneAndUpdate方法传入了回调函数,又搭配了await关键字调用,这会导致Mongoose重复执行同一条查询,所以才会抛出Query was already executed的错误。更新操作第一次执行时已经成功完成,第二次重复执行就触发了报错。
方案1:保留async/await写法(推荐)
移除回调函数,用try/catch捕获异常即可,建议额外添加new: true配置,让接口返回更新后的文档数据:
app.put("/todos/:id", async(req,res) => { try { const { id } = req.params; const { title, content } = req.body.edit; const edit = await Note.findOneAndUpdate( {_id:id}, { title, content }, { new: true } // 配置返回更新后的文档 ) console.log("Successfully edit item:" + edit); res.json(edit); } catch (error) { console.error(error); res.status(500).json({msg: '更新失败', error}) } });
方案2:保留回调写法
移除await关键字即可:
app.put("/todos/:id", (req,res) => { const { id } = req.params; const { title, content } = req.body.edit; Note.findOneAndUpdate( {_id:id}, { title, content }, { new: true }, function (err, docs) { if(!err){ console.log("Successfully edit item:" + docs); res.json(docs); }else{ console.error(err); res.status(500).json({msg: '更新失败', error: err}) } } ) });
内容的提问来源于stack exchange,提问作者Yu Hien Ng
相关产品推荐
相关产品推荐

