Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update multiple records using mongoosejs in node

I'm having trouble updating multiple records using mongoosejs and node. For some reason, I only update a single record, even if multiple match. I've also noticed that the callback will not fire after .update(). I'm not getting any error messages. What's going on here?

Page.find({status:'queued'})
    .limit(queue_limit-queue.length)
    .update({ status: 'active' },{ multi: true },function(err,num){
        console.log("updated "+num);
        //this callback will never fire, but a single record will be updated and marked as active.                                                                                                 
    });
like image 285
devnill Avatar asked Feb 03 '13 15:02

devnill


1 Answers

Query#update doesn't accept an options parameter, but Model.update does. So you'd want to rewrite this as:

Page.update({status:'queued'}, {status: 'active'}, {multi: true}, 
    function(err, num) {
        console.log("updated "+num);
    }
);

I'm not sure what you were trying to do with the limit call in the chain, but you can't use that in an update.

UPDATE

The above query will update all docs where {status: 'queued'}. Your only choices with update are just the first matching one {multi: false} or all matches {multi: true}.

Sounds like you need to rework things to take docs off your queue one at a time and switch to findOneAndUpdate instead of update so you have access to the doc you've updated from 'queued' to 'active'.

like image 135
JohnnyHK Avatar answered Nov 10 '22 04:11

JohnnyHK