Skip to content

Commit

Permalink
fix creation of LB4 models with auto-generated id
Browse files Browse the repository at this point in the history
- 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š <mbajtoss@gmail.com>
  • Loading branch information
bajtos committed Nov 21, 2019
1 parent 2b1b02f commit 483f31e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/mongodb.js
Expand Up @@ -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() {
Expand Down Expand Up @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions test/objectid.test.js
Expand Up @@ -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
});
});
});

0 comments on commit 483f31e

Please sign in to comment.