Reputation: 1325
Yeah, You might get here thinking "this is rather a duplicated question", it might be indeed, but after about a couple hours searching for the answer of the problem, I fail to find one single answer that actually solve my problems, and to be honest most of the people that asked the same thing. So I'm gonna try to make a different question, so here it goes.
Has anyone actually manage to port the function below described in the mongo doco into the mongodb native driver? I'm using nodejs and I'm having a hard time trying to port this to 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 about the nextObject(), toArray(), forEach() and etc. but still can't successfully port it.
Has anyone actually managed to make this happened with this function? I'm looking for the real answer, I know a lot of people might be also interested.
I'm asking this one in particular, because from my understanding this one is the most "safe" one to use as the other suggestions has some flaws when trying to insert multiple documents at the same time.
And no, this is not for my unique id, i'm still using the ObjectID, i just need a serial number, that will be unique for every record.
If you have done it, please share!!! you will save me a loooootttt of time! :)
thanks
Upvotes: 1
Views: 258
Reputation: 25101
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);
}
});
});
}
Upvotes: 1