mongodb-counter
This is a trivial mongodb auto-increment counter implementation based on MongoDB Documentation.
But this implementation requires Mongo 2.4 because it uses the $setOnInsert operation. Unlike the sample in the documentation, this will allow creating new counters on the fly without initializing the counters to zero.
Install
npm install mongodb-counter
Initialization
// Initialization via mongo URLs of the form: mongodb://user:password@host:port/database var counters = ; // Specifying collection name instead of defaulting to counters collection var counters = ; // Initialization via a pre-created database collection to use var counters = ;
API
; // increments by one, throws away the result ; // increments by 5 throws away the result ; // increment by one and get the new value ; ; // same options with decrement ; ; // update the value. // if you only want to generate unique ids (for URL shortening for example), // a much faster method is getNextUniqueId. It only hits the database every 100 // calls. Ofcourse, this has the side effect that the sequence is not strictly // monotonically increasing in order and there could be gaps when there are crashes // but uniqueness is guaranteed and the ordering will be almost monotonic. This is // suitable for a lot of cases where you just want a small unique ID. { ; });