Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

javascript - Mongoose updateOne() going through okay but not updating

I have this request:

// 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))
})

And I get this response from the request:

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

If you can find it on StackOverflow about the updateOne() method in mongoose I've probably tried it. The document isn't updating no matter what I try.

Edit: I've tried using an ObjectID in the query instead and the same result.

Edit 2: I figured it out. Was using req.body.id instead of req.params.id and I was using parameters to send the request. Thanks everyone for the help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

nModified == 0 implies that you have no user matching this id,

your route is put /api/user/:id but your user id is in req.params.id and not in req.body._id


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...