MongoDB / Mongoose: MarkModified a nested object

2020-07-06 05:06发布

问题:

Unfortunately I don't have a record I can test this on, but I can't find any information on this anywhere.

Say I have a document like this:

{
  email:  {
       type: 'Gmail',
       data: {//freeform data},
    }
}

I want to update doc.email.data. I need to use markModified() or else the data won't save correctly.

Do I mark modified like this?

doc.email.data = newData;
doc.markModified('email.data');
doc.save();

Or do I just do markModified('email') and Mongoose will work out the rest?

回答1:

You need to provide the full path the modified object field, so it should be:

doc.markModified('email.data');