这是我的代码:
router.post('/update_todo', async (req, res) => {
const { todoId, userId, complete } = req.body;
try {
const todo = await Todo.findOneAndUpdate(
{ _id: todoId, userId },
{ $set: { complete: !complete } },
{ new: true } // return latest
).populate('userId', '_id');
console.log('todo pdated', todo)
res.json({ todo })
} catch (error) {
res.status(400).json({ error })
}
})
当我尝试记录时,它返回两次?
todo pdated null
todo pdated { complete: true,
_id: 5c003223ec8c1350b8c77b4f,
text: 'wearasdasd asd 2222',
userId: { _id: 5bf3b0b676bcc8176422e94e },
createdAt: 2018-11-29T18:38:27.156Z,
updatedAt: 2018-11-29T23:31:57.022Z,
__v: 0 }
当我使用 async/await 时,是什么导致此代码返回两次?
最佳答案
试试这个:
router.post('/update_todo', async (req, res) => {
const { todoId, userId, complete } = req.body;
try {
Todo.findOneAndUpdate({_id: todoId,userId:userId},{$set:{complete: !complete}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log('todo updated', doc)
res.json({ doc })
});
} catch (error) {
res.status(400).json({ error })
}
})
关于node.js - mongoose findOneAndUpdate 返回两次,第一次为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53536995/