auto increment in node-mongodb-native using counters collection

我的梦境 提交于 2019-12-11 12:08:56

问题


Is there any way of implementing a counters collection as described in the docs with node-mongodb-native?

I'm trying to avoid doing this by nesting over 9000 callbacks (which IMHO sounds untidy and not-elegant) but the good people who wrote this native driver refused to implement synchronous/blocking calls.

Does the native driver provide a someway to call user defined functions and use their return values during queries? Or could there be an alternate way of extracting a sequential count....maybe solely from an ObjectID()?

Any ideas?

EDIT:
This is not for the _id field (That's taken care of by db.coll.save(x))
I have different types of documents in a collection. Each of these needs its own "type serial" or "type sequence" if you know what i mean.

I've already implemented this (plus other stuff) with afew nested calls as shown bellow. doc is JSON.parse'd from the client. I have to return this doc to the client with an _id (sorted by db.coll.save) and with a typeserial (currently being sorted by db.coll.count as shown bellow)

 ///more nesting Async calls above. 
 db.collection('dox').count( { "type" : doc.type } ,
    function( err , count )
    {
        ///{some err checking code here}
        doc.typeseq = (1+count);
        db.collection('dox').save( doc ,
            function( err , doc )
            {
                ///{more code here}
                ///Finally return JSON.stringified doc with new info/members to client-side
            }
        );
    }
 );

I'd just like to know if there is a more elegant, anti-async way of getting my doc.typeserial


回答1:


I am basically going to slap my comment as an answer:

You only need two callbacks, one to get a predefined atomically retrieved _id and the other to actually insert your document. Once you have your auto increment _id it should always be unique to your inserted document this way

To explain more, when you use findAndModify to $inc and return from the counters collection that _id should then be unique that the running of that script and so the consequental insertion of a document. Basically there would be no race condition in this method.

This does mean you will need some kind of parent function like insertWithAI which will do the first callback of using findAndModify to chain the latter callback of inserting but at the end of the day you should only need two callbacks.




回答2:


I implemented auto-increment with the "optimistic loop" with the help of async whilst which worked fine:

Creating incrementing numbers with mongoDB



来源:https://stackoverflow.com/questions/18372159/auto-increment-in-node-mongodb-native-using-counters-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!