Coleman
Coleman

Reputation: 11

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!

Upvotes: 1

Views: 4684

Answers (4)

Tajs
Tajs

Reputation: 621

In case you've set your DB to strict mode don't forget to add strict:false in options when adding new keys. Otherwise, inserts will be silently ignored. I've just spent 2 hours wondering why my inserts don't get saved in DB despite not throwing any error.

See dos http://mongoosejs.com/docs/guide.html#strict

const conditions = {
    _id
}

const dateToUpdate =  {
    $set: {
        "email": "email",
        "name": "name",
        "avatar": "avatar"
    }
}

const updateRecord = await models.pdDealModel.updateOne(conditions,dateToUpdate,{
        upsert:false,
        strict:false
    }
    
)

Upvotes: 0

Daphoque
Daphoque

Reputation: 4678

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

Upvotes: 1

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

if you want to update a document based on _id you can use findByIdAndUpdate()

const userId = req.body._id;
const user =  { "email": email, "name": name, "avatar": avatar } 
User.findByIdAndUpdate(userId , user, 
    function (err, docs) { 
    if (err){ 
        console.log(err) 
    } 
    else{ 
        console.log("Updated User : ", docs); 
    } 
}); 

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8783

A couple tips:

Try running the same query from mongodb at the command line, see if you get any results. Is the "campaign_id" defined as an ObjectId in your schema? If so, try searching using the ObjectId type.

Try to change the query to :

const ObjectId = require('mongoose').Types.ObjectId; 
  const conditions = {
        _id : new ObjectId(userId)
    }

The reason for not updating is - mongoose is unable to search the with the id you provided.

Upvotes: 0

Related Questions