Skip to content

Commit

Permalink
Merge pull request #553 from strongloop/fix/detect-objectid-from-db
Browse files Browse the repository at this point in the history
fix creation of LB4 models with auto-generated id
  • Loading branch information
bajtos authored Nov 22, 2019
2 parents 2b1b02f + 483f31e commit 3cde61d
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 3cde61d

Please sign in to comment.