Search code examples
javascriptnode.jsmongodbmonk

How to call a mongodb function using monk/node.js?


Tyring to implement this:

http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/#auto-increment-counters-collection

to provide sequence counters for a few things.

I've got the function stored in my db, but I can't call it without an error:

var model_id = db.eval('getNextSequence("model")');

Returns:

Object # has no method 'getNextSequence'

Is this because monk doesn't support the use of db functions via eval?


Solution

  • The getNextSequence method is part of your application code and runs in your application, not in the database. In the example from the mongodb docs, that application is the mongo shell which is basically a simple javascript-wrapper where you can easily declare your own methods.

    In any case, implementing reliable, gap-free counters isn't trivial and should be avoided unless absolutely required:

    1. incrementing a counter before insert will lead to gaps if the subsequent insert fails because of client crash, network partition, etc.
    2. incrementing the counter after insert requires an optimistic insert loop (but doesn't require an explicit counter, as demonstrated in the link). This is more reliable, but gets inefficient with concurrent writers because it performs lots of queries and failed updates.

    In a nutshell, such counters are OK if you're using them e.g. within a single account / tenant where the users of an account are humans. If your accounts are huge or if you have API clients, things get messy because they might burst and do 10,000 inserts in a few seconds which leads to a whole lot of conflicts.

    Never use increment keys as primary keys.