Fix removeUndefined to bypass non-plain objects

traverse.map() transform custom objects such as Date or ObjectID into
plain objects and it breaks the BSON serialization
This commit is contained in:
Raymond Feng 2013-10-29 22:16:43 -07:00
parent dff3367f3a
commit d0055d8591
2 changed files with 17 additions and 4 deletions

View File

@ -69,7 +69,7 @@ function selectFields(fields) {
result[key] = obj[key]; result[key] = obj[key];
} }
return result; return result;
} };
} }
/** /**
@ -81,10 +81,19 @@ function removeUndefined(query) {
if (typeof query !== 'object' || query === null) { if (typeof query !== 'object' || query === null) {
return query; return query;
} }
return traverse(query).map(function (x) { // WARNING: [rfeng] Use map() will cause mongodb to produce invalid BSON
// as traverse doesn't transform the ObjectId correctly
return traverse(query).forEach(function (x) {
if (x === undefined) { if (x === undefined) {
this.remove(); this.remove();
} }
if (!Array.isArray(x) && (typeof x === 'object' && x !== null && x.constructor !== Object)) {
// This object is not a plain object
this.update(x, true); // Stop navigating into this object
return x;
}
return x; return x;
}); });
} }

View File

@ -46,6 +46,10 @@ describe('util.removeUndefined', function(){
should.equal(removeUndefined('x'), 'x'); should.equal(removeUndefined('x'), 'x');
var date = new Date();
var q4 = {where: {x: 1, y: date}};
should.deepEqual(removeUndefined(q4), {where: {x: 1, y: date}});
}); });
}); });