首页 > 解决方案 > Mongoose updateOne() 正常但没有更新

问题描述

我有这个要求:

// PUT that updates a user. 
router.put('/api/user/:id', async (req: Request, res: Response) => {
    const { email, name, avatar } = req.body

    const userId = req.body._id
    const conditions = {
        _id : userId
    }

    const user = {$set: { "email": email, "name": name, "avatar": avatar } }
    
    User.updateOne(conditions, user).then(doc => {
        if (!doc) { return res.status(404).end() }
        return res.status(200).json(doc)
    }).catch(error => console.log(error))
})

我从请求中得到了这个响应:

{
    "n": 0,
    "nModified": 0,
    "ok": 1
}

如果您可以在 StackOverflow 上找到有关 mongoose 中的updateOne()方法的信息,我可能已经尝试过。无论我尝试什么,该文档都不会更新。

编辑:我尝试在查询中使用 ObjectID,结果相同。

编辑2:我想通了。正在使用 req.body.id 而不是 req.params.id 并且我正在使用参数来发送请求。感谢大家的帮助!

标签: javascriptnode.jsmongodbmongoose

解决方案


nModified == 0表示您没有匹配此 ID 的用户,

您的路线是put /api/user/:id,但您的用户 ID 在 req.params.id 而不是 req.body._id


推荐阅读