0

I need to make a patch request to update only one (or several) field(s) at the same time. I've got a big object which is my document, and inside nested array of objects.

For example, for my car array, this is the schema :

const carSchema = new Schema({
  owner: [{value: {type: String}, label: {type: String}}],
  carPlate: {type: String},
  carColor: {type: String},
  carBrand: {type: String},
  carStatus: {type: String}
});

const myObject = new Schema({
...
cars: [carSchema]
...
});

When I send my changes, I do it this way :

let dynamicVar = 'cars.'+i+'.'+myfield; this.props.updateGeneral({_id: this.props.general._id, [dynamicVar ]: [myfield.value]});

I'm on redux, so my action looks like :

export function updateGeneral(data) {
    let _id = data._id;
    delete data._id;
    return {
        type: 'UPDATE_GENERAL',
        payload: client.patch(`${url}/${_id}`, data)
    }
}

And my PATCH request is like :

router.patch('/url/:id', async (req, res, next) => {
myObject.findOneAndUpdate({_id: req.params.id}, {$set: req.body }, {upsert: true, new: true}, function (err, objectReturn) {
    if (err) return next(err);
    cn = cn.substr(0, cn.indexOf(' {'));
    res.json(objectReturn);

  });
});

My BIG issue is that my field is update or inserted, but if it's inserted and it creates a new array it won't create the objectId linked. It won't even create the array of object,just an object with a property.

How can I make mongoose initiates ObjectId??

So4ne
  • 1,124
  • 17
  • 38

1 Answers1

0

Per the reply to this SO post it looks like you cannot update object IDs. When doing so, you are effectively "deleting" the object and creating a new one.

Pytth
  • 4,008
  • 24
  • 29