From 1a65a51af2fa5c5d48c252093c20cf638b68fdc5 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Mon, 18 Aug 2014 09:25:19 +0200 Subject: [PATCH] Created _id cannot be equal to another id --- lib/datastore.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/datastore.js b/lib/datastore.js index cade891..7ca8226 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -289,6 +289,18 @@ Datastore.prototype._insert = function (newDoc, cb) { }); }; +/** + * Create a new _id that's not already in use + */ +Datastore.prototype.createNewId = function () { + var tentativeId = customUtils.uid(16); + // Try as many times as needed to get an unused _id. As explained in customUtils, the probability of this ever happening is extremely small, so this is O(1) + if (this.indexes._id.getMatching(tentativeId).length > 0) { + tentativeId = this.createNewId(); + } + return tentativeId; +}; + /** * Prepare a document (or array of documents) to be inserted in a database * @api private @@ -300,7 +312,7 @@ Datastore.prototype.prepareDocumentForInsertion = function (newDoc) { preparedDoc = []; newDoc.forEach(function (doc) { preparedDoc.push(self.prepareDocumentForInsertion(doc)); }); } else { - newDoc._id = newDoc._id || customUtils.uid(16); + newDoc._id = newDoc._id || this.createNewId(); preparedDoc = model.deepCopy(newDoc); model.checkObject(preparedDoc); } @@ -578,4 +590,5 @@ Datastore.prototype.remove = function () { + module.exports = Datastore;