0

So I was basically trying to update/save values to mongoDb depending on what the user entered. More specifically, if the user entered a name that was already on the database, then that value gets updated with the newly entered one, but if the value was not on the database then it just saves it to the db. I already looked at a couple SO posts such as this and that but still don't quite get it because the way their errors formed differs a bit from mine. The error I am getting is: "MongoServerError: Plan executor error during findAndModify :: caused by :: Performing an update on the path '_id' would modify the immutable field '_id'".

Any help would be greatly appreciated.

app.post('/api/persons',(req,res) => {
    const newPerson = req.body;

    const nperson = new Person({
        name: newPerson.name,
        number: newPerson.number
    })


    Person.find({name:newPerson.name}).then((result) => {
        console.log("nperson at top is",nperson)
        console.log("top most is", result)
        if(result){
            const idToUpdate = result[0]._id.toString(); //Got the correct id but it still does not work
            Person.findByIdAndUpdate(idToUpdate, nperson,{ new: true })
                .then((updatedPerson) => {
                    console.log("Person successfully updated!");
                    res.status(200).json(updatedPerson)
                })
                .catch((error) => {
                    console.log(error);
                    res.status(400).json({error: "Could not update person"}) //This is currently the response I get back
                })
        }
        else {
            nperson.save().then((result) => {
            console.log("Saved person to MongoDB!")
            res.status(200).json(result)
            })
        }
    })

1 Answers1

0

For this question, you cannot have nperson as a new Person object as a new id is then generated with it so you have to turn it into

 var nperson = {
        name: newPerson.name,
        number: newPerson.number
    }

And also add this portion into the else block

else {
            nperson = new Person({
                    name: newPerson.name,
                    number: newPerson.number
            })

            nperson.save().then((result) => {
            console.log("Saved person to MongoDB!")
            res.status(200).json(result)
            })
        }

And then everything works as expected.