Search code examples
node.jsmongodbmongooseinsert-update

Node.js/Express: mongoose/mongoDB update document with req.body but avoid updating _id field?


I am currently trying to update a document based on some _id value. If found, I want to update evreything with req.body, except setting a new _id (I want to avoid, that client can update their _id). So how can I do this? Would I update all fields manually and exclude _id field? Currently I am doing this:

exports.updateDemoStatus = function(req, res) {
    Status.findOneAndUpdate({Demonstrator: req.params.demo_id}, req.body, {new: true}, function(err, status) {
        if (err)
            console.log(status);
        res.json(status);       
    });
};

Solution

  • Updating a document won't change it's _id field since it's unique and related to that specific document.

    Please refer to the documentation. As suggested on the Mongoose official docs, if you need full-fledged validation, use the traditional approach of first retrieving the document.