javascript - Mongoose - save document Object.assign - Stack Overflow

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

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...

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...

Share Improve this question edited Sep 22, 2017 at 17:57 CommunityBot 11 silver badge asked May 8, 2017 at 14:48 Maxwell s.cMaxwell s.c 1,66816 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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");
        });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742310001a4419699.html

相关推荐

  • javascript - Mongoose - save document Object.assign - Stack Overflow

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

    14小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信