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 + }); }); });