9

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

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

3 Comments

The point of the limit is to make it so I only update 10 records. Your query looks like it would update everything with {status:'queued'}. I also need the first callback I used in my example to see what records I'm changing (and not just the number affected).
@Sammaye: Thanks, I was worried about that. What are the current best practices for something like this?
@devnill The edit seems to do a good job of answering that, unfortunately it is not an easy thing to do and there is no easy right way atm

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.