cplus
cplus

Reputation: 1115

mongoose find and save not updating the document

I am using mongoose to find and modify and save back to the collection. Here is what I have tried:

if(req.body.writer){
     MyModel.find({writer: req.body.oldname},function (err, data) {
                for(var i = 0; i < data.length; i++){
                    data[i].writer= req.body.newName;
                    data[i].save()                    
                }
            });
}

why is this not updating the document? where is the problem lying? thanks

Upvotes: 0

Views: 398

Answers (1)

Mihir Bhende
Mihir Bhende

Reputation: 9045

Try update method :

if(req.body.writer && req.body.newName){
     MyModel.update(
        //search documents with old writer
        { writer : req.body.oldname},
        // set writer as newName
        { $set : { writer : req.body.newName} },
        {"multi": true},
        //check for error
        function (err) {
            if(err){
                res.status(500).send(err);
            }
            else{
                res.status(200).send('updated successfully..');
            }
        }
    );
}

Upvotes: 1

Related Questions