devnill
devnill

Reputation: 2123

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

Upvotes: 9

Views: 16733

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

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

Upvotes: 17

Related Questions