MongoDB remove not working until 2nd attempt?

I’m having a very strange issue I have never ran in to before…

We have a very basic function in our app. You put in a productId, it finds an order with that productId, and then remove it.

Here is an excerpt of the code:

// check if existing special order
    var special = SpecialOrdersCollection.findOne({productId: productId});

    // if none are needed
    if (needed == 0) {

        if (special == undefined) {
            // DEPRECATED - do nothing?
        } else {
            // remove
            SpecialOrdersCollection.remove({_id: special._id});

            console.log("SpecialOrders_Update - REMOVE complete - " + special._id);


Now the above code is running properly. It’s giving us the console.log - so all data it needs should be there.

But the first time we run that code - the item is not deleted. We gave it extra time to see, and manually checked database. The item is still there.

Yet if we run the function a second time, it removes properly. No issues.

My only guess is there could have been a 2nd item with the same productId? But when searching the database, I only found one? And now that I think about it, remove should be removing multiple ones with that productId anyway, no?

I’m stumped on this one, any ideas why this could be happening?

(Edit: Of course figured it out right after posting. The findOne was deleting it’s own _id, so it’s likely possible that there was a 2nd piece of data with a matching productId.)

Is this on the server? Check out the docs?

On the server, if you don’t provide a callback, then remove blocks until the database acknowledges the write and then returns the number of removed documents, or throws an exception if something went wrong. If you do provide a callback, remove returns immediately. Once the remove completes, the callback is called with a single error argument in the case of failure, or a second argument indicating the number of removed documents if the remove was successful.

SpecialOrdersCollection.remove(special._id, function(err, res){
  if(err) console.log(err);
  else console.log("SpecialOrders_Update - REMOVE complete - " + special._id + " " + res);

Edit: didn’t see that you had updated your own post already