Fix bug in utils uniq function (#1526)
The uniq function does currently not work when the database is mongodb. In the case of mongodb, the function will receive an array of bson object of bson type ObjectID. The indexOf function will return a different index, even if the mongodb ID is the same, as it is wrapped in the ObjectID. This commit first transforms any ObjectID in the array to a string representation. We can then use indexOf to check for uniqueness.
This commit is contained in:
parent
7a4c6ca2f9
commit
6bd9fca080
|
@ -566,8 +566,10 @@ function uniq(a) {
|
|||
return uniqArray;
|
||||
}
|
||||
assert(Array.isArray(a), 'array argument is required');
|
||||
for (var i = 0, n = a.length; i < n; i++) {
|
||||
if (a.indexOf(a[i]) === i) {
|
||||
var comparableA = a.map(
|
||||
item => item.hasOwnProperty('_bsontype') ? item.toString() : item);
|
||||
for (var i = 0, n = comparableA.length; i < n; i++) {
|
||||
if (comparableA.indexOf(comparableA[i]) === i) {
|
||||
uniqArray.push(a[i]);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,6 +33,7 @@
|
|||
},
|
||||
"devDependencies": {
|
||||
"async-iterators": "^0.2.2",
|
||||
"bson": "^1.0.4",
|
||||
"coveralls": "^2.13.1",
|
||||
"eslint": "^3.12.2",
|
||||
"eslint-config-loopback": "^8.0.0",
|
||||
|
|
|
@ -6,6 +6,7 @@
|
|||
'use strict';
|
||||
var should = require('./init.js');
|
||||
var utils = require('../lib/utils');
|
||||
var ObjectID = require('bson').ObjectID;
|
||||
var fieldsToArray = utils.fieldsToArray;
|
||||
var removeUndefined = utils.removeUndefined;
|
||||
var deepMerge = utils.deepMerge;
|
||||
|
@ -424,6 +425,15 @@ describe('util.uniq', function() {
|
|||
b.should.eql(['a', 'b']);
|
||||
});
|
||||
|
||||
it('should dedupe an array with duplicate bson entries', function() {
|
||||
var idOne = new ObjectID('59f9ec5dc7d59a00042f7c62');
|
||||
var idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63');
|
||||
var a = [idOne, idTwo, new ObjectID('59f9ec5dc7d59a00042f7c62'),
|
||||
new ObjectID('59f9ec5dc7d59a00042f7c62')];
|
||||
var b = uniq(a);
|
||||
b.should.eql([idOne, idTwo]);
|
||||
});
|
||||
|
||||
it('should dedupe an array without duplicate number entries', function() {
|
||||
var a = [1, 3, 2];
|
||||
var b = uniq(a);
|
||||
|
@ -436,6 +446,15 @@ describe('util.uniq', function() {
|
|||
b.should.eql(['a', 'c', 'b']);
|
||||
});
|
||||
|
||||
it('should dedupe an array without duplicate bson entries', function() {
|
||||
var idOne = new ObjectID('59f9ec5dc7d59a00042f7c62');
|
||||
var idTwo = new ObjectID('59f9ec5dc7d59a00042f7c63');
|
||||
var idThree = new ObjectID('59f9ec5dc7d59a00042f7c64');
|
||||
var a = [idOne, idTwo, idThree];
|
||||
var b = uniq(a);
|
||||
b.should.eql([idOne, idTwo, idThree]);
|
||||
});
|
||||
|
||||
it('should allow null/undefined array', function() {
|
||||
var a = null;
|
||||
var b = uniq(a);
|
||||
|
|
Loading…
Reference in New Issue