1

I'd like to replace an object in an array using an index, but nothing will save. This is what the document looks like:

{
    "_id": {
        "$oid": "58a71ec0c80a9a0436ae2fb1"
    },
    "owner": "[email protected]",
    "contacts": [
        {
            "work": "",
            "home": "",
            "mobile": "",
            "email": "",
            "company": "",
            "last": "Contact",
            "middle": "",
            "first": "New"
        },
        {
            "first": "Another",
            "middle": "",
            "last": "Contact",
            "company": "",
            "email": "",
            "mobile": "",
            "home": "",
            "work": ""
        }
    ],
    "__v": 1
}

And this is what I've tried..

Contacts.findById({_id: "58a71ec0c80a9a0436ae2fb1"}, function(err,document) {
    document.contacts[req.body.indexOfObjectToBeEdited] = req.body.updatedObject
    console.log(document)
    document.save(function(err) {
        return res.json({event:"Updated Contact"})
    })
})

Right before document.save() I console.log(document) and it reflects the correct changes. But when I save, nothing is updated in the mongodb and I receive no errors. What should I be doing differently?

2
  • What do you mean when you say "when I print"? You mean after the save function? Commented Feb 17, 2017 at 16:32
  • Right before document.save, I will console.log(document) and it looks updated. But when I check the db after actually saving, it looks like it was never updated. Commented Feb 17, 2017 at 16:33

1 Answer 1

4

try inserting this line right before saving. As modifying an array require we need to manual tell the mongoose the it is modified.

document.markModified("contacts");

Check the Usage Notes in the documentation for more information http://mongoosejs.com/docs/schematypes.html

Sign up to request clarification or add additional context in comments.

2 Comments

Learned something new!
Thanks @Rohail Najam, you saved my sanity. I tried to update an array with a new one in every way without success, and "markModified" did the work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.