Skip to content

Commit

Permalink
Merge pull request #582 from strongloop/array/objid
Browse files Browse the repository at this point in the history
fix: coerce property value defined as array of ObjectID
  • Loading branch information
agnes512 committed Jul 10, 2020
2 parents c025814 + 78e7970 commit b12633b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
4 changes: 2 additions & 2 deletions lib/mongodb.js
Expand Up @@ -2151,12 +2151,12 @@ function coercePropertyValue(modelCtor, propValue, propDef, setValue) {
if (Array.isArray(propValue)) {
propValue = propValue.map(val => {
if (isObjectIDProperty(modelCtor, propDef, val)) {
return coercedValue = ObjectID(propValue);
return coercedValue = ObjectID(val);
} else {
throw new Error(`${val} is not an ObjectID string`);
}
});
return setValue(coercedValue);
return setValue(propValue);
} else if (isObjectIDProperty(modelCtor, propDef, propValue)) {
coercedValue = ObjectID(propValue);
return setValue(coercedValue);
Expand Down
20 changes: 17 additions & 3 deletions test/objectid.test.js
Expand Up @@ -10,6 +10,8 @@ require('./init.js');
let Book, Chapter;
const ds = global.getDataSource();
const objectIDLikeString = '7cd2ad46ffc580ba45d3cb1f';
const objectIDLikeString2 = '7cd2ad46ffc580ba45d3cb1e';
const promisify = require('bluebird').promisify;

describe('ObjectID', function() {
before(function() {
Expand Down Expand Up @@ -131,11 +133,19 @@ describe('ObjectID', function() {
it('should properly save an array of ObjectIDs', async () => {
await Article.create({
xid: objectIDLikeString,
xidArr: [objectIDLikeString],
xidArr: [objectIDLikeString, objectIDLikeString2],
title: 'arrayOfObjectID',
});
const found = await Article.findOne({where: {title: 'arrayOfObjectID'}});
found.xidArr.should.be.an.Array().which.containDeep([new ds.ObjectID(objectIDLikeString)]);
const found = await Article.find({where: {title: 'arrayOfObjectID'}});
// the type of the returned array is actually string even it's stored as ObjectIds in the db as expected
found[0].xidArr.should.containDeep([
new ds.ObjectID(objectIDLikeString),
new ds.ObjectID(objectIDLikeString2),
]);
// check if the array is stored in ObjectId
const raw = await findRawModelDataAsync('ArticleC', found[0].id);
raw.xidArr[0].should.be.an.instanceOf(ds.ObjectID);
raw.xidArr[1].should.be.an.instanceOf(ds.ObjectID);
});

it('handles auto-generated PK properties defined in LB4 style', async () => {
Expand Down Expand Up @@ -188,4 +198,8 @@ describe('ObjectID', function() {
found.xidArr.should.be.an.Array().which.containDeep([new ds.ObjectID(objectIDLikeString)]);
});
});
function findRawModelData(modelName, id, cb) {
ds.connector.execute(modelName, 'findOne', {_id: {$eq: id}}, {safe: true}, cb);
}
const findRawModelDataAsync = promisify(findRawModelData);
});

0 comments on commit b12633b

Please sign in to comment.