node.jsmongodbmongooseupdatemodel

Mongoose autoincrement confusion


I'm a novice at Mongoose so with that in mind ...

I am trying to update data in a document without success. The code below identifies the document as I expect and changes the model as expect. However the updated model is not saved to MongoDB and I am at a loss to explain why ... (Perhaps I should be using the findOneAndUpdate instruction but working piecemeal like this is easier to follow.)

UserModel.findOne({memberID: req.params.memberID}, function(err, foundObject) {
        if(err) {
            console.log('ERROR PUT:/updateUser -> ' + err);
            res.status(500).send();
        } else {
            if(!foundObject) {
                console.log('ERROR - PUT:/updateUser, No such record -> ' + req.params.memberID);
                res.status(500).send();
            } else {
                console.log("1 :" + foundObject.info.fName);
                if(req.body.fName)
                    foundObject.info.fName = req.body.fName;
                console.log("2 :" + foundObject.info.fName);

                foundObject.update(function(err, updatedObject) {
                    if(err) {
                        console.log('ERROR - PUT:/updateUser, SAVE FAIL -> ' + err);
                        res.status(500).send();
                    } else {
                        res.status(200).send(updatedObject);
                    }
                });
            }
        }
    });

The output from Postman (which I am using to test) is { "ok": 1, "nModified": 0, "n": 1 } and a direct, console query on the db shows no change.


Solution

  • Can try this one.

    UserModel.findOneAndUpdate({memberID: req.params.memberID}, {$set: {"info.fName" : req.body.fName}}, {new: true})
        .exec(function (error, updatedUser) {
            if (error) {
                return res.status(400).send({msg: 'Update failed'});
            }
            return res.status(200).send(updatedUser);
        });
    

    N.B: Ensure that req.params.memberID and req.body.fName got correctly