node.js - Auto-increment in Native MongoDB -
yeah, might here thinking "this rather duplicated question", might indeed, after couple hours searching answer of problem, fail find 1 single answer solve problems, , honest of people asked same thing. i'm gonna try make different question, here goes.
has manage port function below described in mongo doco mongodb native driver? i'm using nodejs , i'm having hard time trying port it's native driver.
function insertdocument(doc, targetcollection) { while (1) { var cursor = targetcollection.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1); var seq = cursor.hasnext() ? cursor.next()._id + 1 : 1; doc._id = seq; targetcollection.insert(doc); var err = db.getlasterrorobj(); if( err && err.code ) { if( err.code == 11000 /* dup key */ ) continue; else print( "unexpected error inserting data: " + tojson( err ) ); } break; } }
i read nextobject(), toarray(), foreach() , etc. still can't port it.
has managed make happened function? i'm looking real answer, know lot of people might interested.
i'm asking 1 in particular, because understanding 1 "safe" 1 use other suggestions has flaws when trying insert multiple documents @ same time.
and no, not unique id, i'm still using objectid, need serial number, unique every record.
if have done it, please share!!! save me loooootttt of time! :)
thanks
try this:
function insertdocument(doc, collection) { collection.find({}, { limit: 1, fields: { _id: 1 }, sort: { _id: -1 } }).toarray(function (err, docs) { var _next = docs.length ? docs[0]._id + 1 : 1; doc._id = _next; collection.insert(doc, function (err, result) { if (err && err.message.indexof('11000') > -1) { //try again insertdocument(doc, collection); } }); }); }
Comments
Post a Comment