Document Increment Sequence is skipping numbers


#1

I’m currently having issues when querying/inserting for one of my Documents inside a Database through Meteor.

Using this line of code I’m trying to retrieve the next sequence number out of the DB. But it sometimes skips numbers for some reason.

var col = MyCounters.findOne(type);
MyCounters.update(col._id, {$inc: {seq: 1}});
return col.seq;

Then I update another Collection with the new value obtained from MyCounters collection, so it would be something like this:

var col = MyCounters.findOne(type);
MyCounters.update(col._id, {$inc: {seq: 1}});
var barId = col.seq;

// declare barObject + onInsertError
barObject.barId = barId;
// ...
FooCollection.insert(barObject, onInsertError);

And FooCollection ends up having skipped sequence numbers up to 5000 sometimes.
Not getting any kind of errors server side.

Does anybody know what the issue might be? I ruled out a possible race condition catching any errors that may be happening during this Insert, but none show up.

It also only occurs on our production environment, but I can’t reproduce it on local/staging env.

I’m on Meteor 1.4+ and Mongo 3.0.11


#2

edit: Misread.

I think I know what’s happening but to be sure a question: How busy is your production env, i.e. how many users?


#3

That is not atomic, and will be worse if you have multiple server instances in production. This post may help:


#4

I thought that findAndModify was not supported by meteor yet.


#5

It’s fine on the server when using rawCollection. You can’t use it with minimongo.


#6

Thanks @robfallows, I’ll try this out and update on my results.


#7

Since the update to the latest node MongoDB library in Meteor 1.4, it’s also possible to use Promises directly from the rawCollection. If you’re more comfortable with those, rather than Meteor.wrapAsync, you may find that useful.