From 483f31ebf2d036d0c4ddc6379f43b9199e3edef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Thu, 21 Nov 2019 17:27:27 +0100 Subject: [PATCH] fix creation of LB4 models with auto-generated id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add a try/catch block to prevent `coerceId` from crashing the process on uncaught exception (forward the coercion error via callback). - Fix `isObjectIDProperty` to use the correct ObjectID constructor in `instanceof` check. Signed-off-by: Miroslav Bajtoš --- lib/mongodb.js | 10 ++++++++-- test/objectid.test.js | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/mongodb.js b/lib/mongodb.js index 9487d8d9d..dd4e2e4f4 100644 --- a/lib/mongodb.js +++ b/lib/mongodb.js @@ -596,7 +596,13 @@ MongoDB.prototype.create = function(modelName, data, options, callback) { return callback(err); } idValue = result.ops[0]._id; - idValue = self.coerceId(modelName, idValue, options); + + try { + idValue = self.coerceId(modelName, idValue, options); + } catch (err) { + return callback(err); + } + // Wrap it to process.nextTick as delete data._id seems to be interferring // with mongo insert process.nextTick(function() { @@ -1963,7 +1969,7 @@ function isObjectIDProperty(modelCtor, propDef, value, options) { if (typeof value === 'string' && value.match(ObjectIdValueRegex)) { if (isStoredAsObjectID(propDef)) return true; else return !isStrictObjectIDCoercionEnabled(modelCtor, options); - } else if (value instanceof ObjectID) { + } else if (value instanceof mongodb.ObjectID) { return true; } else { return false; diff --git a/test/objectid.test.js b/test/objectid.test.js index 53f925f27..ba8dcb1a3 100644 --- a/test/objectid.test.js +++ b/test/objectid.test.js @@ -126,5 +126,23 @@ describe('ObjectID', function() { const found = await Article.findOne({where: {title: 'abc'}}); found.xid.should.be.an.instanceOf(ds.ObjectID); }); + + it('handles auto-generated PK properties defined in LB4 style', async () => { + const Note = ds.createModel('NoteLB4', { + id: { + type: 'string', + id: true, + generated: true, + mongodb: {dataType: 'ObjectID'}, + }, + title: { + type: 'string', + required: true, + }, + }); + + const result = await Note.create({title: 'hello'}); + // the test passes when this call does not throw + }); }); });