'How to update a subdocument (REF)?

I'm using the method below to update all the fields in the "Producers" document.

exports.updateProducers = async (req, res) => {
    let obj = new Producers(req.body);
    await Producers.findOneAndUpdate({ "user.nome": "Naomi"}, obj, {upsert: true, new: true}, function (err) {
        (err ? res.status(400).send(err) : res.status(200).json(obj));
    });
}

This method works and normally updates all the "Producers" fields, however, I have a reference to the "User" document, done like this:

user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },

In "Users", I have the "name" field. How can I add editing on users as well?

I'm currently getting this message:

MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

I appreciate if anyone can help me analyze what I'm doing wrong?



Solution 1:[1]

Friend when you created the instance of product like you did with obj, you only created a temp instance and that instance was not saved into the database, so the used method to update, only needs a filter and the update, and a few optional parameters, so if you want to update from a property like name or something else, use this instead:

const resultOfUpdate = await Producers.findOneAndUpdate(
    {
        "users.name": "Naomi"
    },
    obj,
    {
        upsert: true,
        new: true
    }
)

Use REST API approach to have a good understanding on how to update a document, for more details, check out these sources:

https://www.geeksforgeeks.org/mongoose-findbyidandupdate-function/ https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P