I'm getting Query was already executed error when using findByIdAndUpdate in mongoose to update a todo list.
Console
/Users/ariful/dev/todo/node_modules/mongoose/lib/helpers/query/wrapThunk.js:21
const err = new MongooseError('Query was already executed: ' str);
^
MongooseError: Query was already executed: Todo.findOneAndUpdate({ _id: new ObjectId("62eb7849edd528678...
at model.Query._wrappedThunk [as _findOneAndUpdate] (/Users/ariful/dev/learn/todo/node_modules/mongoose/lib/helpers/query/wrapThunk.js:21:19)
at /Users/ariful/dev/learn/todo/node_modules/kareem/index.js:426:25
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
originalStack: 'Error\n'
' at model.Query._wrappedThunk [as _findOneAndUpdate] (/Users/ariful/dev/learn/todo/node_modules/mongoose/lib/helpers/query/wrapThunk.js:25:28)\n'
' at /Users/ariful/dev/learn/todo/node_modules/kareem/index.js:426:25\n'
' at process.processTicksAndRejections (node:internal/process/task_queues:77:11)'
}
My Code:
Todo Controller
// PUT TODO
router.put('/:id', async (req, res) => {
// Update a todo
const result = await Todo.findByIdAndUpdate(
{ _id: req.params.id },
{
$set: {
status: "active",
},
},
{
new: true, // for getting updated result
},
(err) => {
if (err) {
res.status(500).json({
error: "Opps! - can't create todo some error happend!"
})
} else {
res.status(200).json({
message: "Todo updated sucessful!"
});
}
}
)
console.log(result);
})
After executing put request the server crashes but the value updated in the database.
CodePudding user response:
You are using async await style, so put the code inside try/catch
block.
This should work without an error
try {
const result = await Todo.findByIdAndUpdate(
{ _id: req.params.id },
{
$set: {
status: "active",
},
})
res.status(200).json({ message: "Todo updated sucessful!"});
} catch (error) {
res.status(500).json({
error: "Opps! - can't create todo some error happend!"
})
}