我有这种代码。当我搜索find()时,使用findOne()搜索时不起作用。 感谢您的回答!
const task = await Task.find({_id, owner: req.user._id}) //This does not work
const task = await Task.findOne({_id, owner: req.user._id}) // This works
router.patch('/tasks/:id', auth, async (req, res) => {
const updates = Object.keys(req.body) // The opposite is Object.values()
const _id = req.params.id
const allowedUpdates = ['description', 'completed']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({error: 'Invalid update!'})
}
try {
const task = await Task.findOne({_id, owner: req.user._id})
if (!task) {
return res.status(404).send()
}
updates.forEach((update) => task[update] = req.body[update])
await task.save()
res.send(task)
} catch (e) {
res.status(500).send(e)
}
})