4

I have a mongoose document, and i want to update many fields on it with another object. something like

Model.findById(_id, function (err, doc){
    var updateData = {...data}

    // i do not want to do 
    doc.foo = data.foo;
    doc.bar = data.bar;

    // i need something like
    doc.save(updateData)
    // or
    doc.update(updateData)
    // or
    doc = {...doc, ...updateData}
    doc.save();

});

the updateData is a object with all the data i need to update in the doc.

didn't found any doc related, the closest was a find one and update...

2 Answers 2

6

Assuming your data object has all of the keys you want to update on the document, why don't you try using Object.assign as you mention in the title of your question:

Object.assign(doc, data);
doc.save(callback); // save is async

Or you can use Mongo's .findByIAndUpdate() like so:

Model.findByIdAndUpdate(id, { $set: data }, callback)

Either way, you can avoid manually setting each property you want to update.

6
  • 5
    but i'm afraid the Object.assign may override the setters/getters or any important properties of the mongoose object. This will happens? May 9, 2017 at 20:32
  • 1
    I think you should be okay per the Object.assign documentation. Object.assign uses get on the source and set on the target (in this case, your document), therefore it assigns properties verses just copying them, so it should adhere to any predefined getters/setters
    – Ian
    May 9, 2017 at 20:40
  • 1
    Great! i was thinking in use spread operator, something like {..doc, ...data} but this will create another object and won't keep the mongoose doc. May 10, 2017 at 14:15
  • 1
    But I have one last question to confirm, using Object.assign(doc, data), nested objects will be replaced or they will obey the getters/setters from mongoose document? May 10, 2017 at 14:17
  • 1
    @AdamD yes i think. i made this question long ago and don't remember but i checked it as the correct answer so it works Mar 12, 2019 at 1:52
0

try this

// update

router.put("/updatestudent/:id", function(req, res) {
    var id = req.params.id;
    var obj = req.body;
    student.findByIdAndUpdate(id, { name: obj.name, emailid: obj.emailid },
        function(err) {
            if (err) {
                return res.send('error updated student');
            }
            res.send("updated");
        });
});
1
  • 1
    sorry, but i need to work with the current object, i'm trying to not search the item again May 9, 2017 at 20:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.