Skip to content
This repository has been archived by the owner on Feb 3, 2022. It is now read-only.

Commit

Permalink
fix(serialize): properly serialize BSON types when used as values
Browse files Browse the repository at this point in the history
closes #1
  • Loading branch information
mbroadst committed May 24, 2017
1 parent 7ddaf20 commit 66fe3d9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
24 changes: 15 additions & 9 deletions lib/ext_json.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,21 +199,27 @@ var BSONTypes = ['Binary', 'Code', 'DBRef', 'Decimal128', 'Double',
'Int32', 'Long', 'MaxKey', 'MinKey', 'ObjectID', 'BSONRegExp', 'Symbol', 'Timestamp'];

function serializeDocument(doc) {
if(doc == null || typeof doc !== 'object') throw new Error('not an object instance');
var _doc = {};
if (doc == null || typeof doc !== 'object') {
throw new Error('not an object instance');
}

if (doc != null && doc._bsontype && BSONTypes.indexOf(doc._bsontype) != -1) {
return doc.toJSON();
}

for(var name in doc) {
if(Array.isArray(doc[name])) {
var _doc = {};
for (var name in doc) {
if (Array.isArray(doc[name])) {
_doc[name] = serializeArray(doc[name]);
} else if(doc[name] != null && doc[name]._bsontype && BSONTypes.indexOf(doc[name]._bsontype) != -1) {
} else if (doc[name] != null && doc[name]._bsontype && BSONTypes.indexOf(doc[name]._bsontype) != -1) {
_doc[name] = doc[name];
} else if(doc[name] instanceof Date) {
} else if (doc[name] instanceof Date) {
_doc[name] = serializeValue(doc[name]);
} else if(doc[name] != null && typeof doc[name] === 'object') {
} else if (doc[name] != null && typeof doc[name] === 'object') {
_doc[name] = serializeDocument(doc[name]);
} else {
_doc[name] = serializeValue(doc[name]);
}

_doc[name] = serializeValue(doc[name]);
}

return _doc;
Expand Down
15 changes: 15 additions & 0 deletions test/extend_mongodb_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,21 @@ describe('Extended JSON', function() {
assert.equal(10, doc2.int32);
});

it('should correctly serialize bson types when they are values', function() {
// Create ExtJSON instance
var extJSON = new ExtJSON();
var Int32 = ExtJSON.BSON.Int32,
ObjectId = ExtJSON.BSON.ObjectID;

var serialized = extJSON.stringify(new ObjectID('591801a468f9e7024b6235ea'));
assert.equal(serialized, '{"$oid":"591801a468f9e7024b6235ea"}');
serialized = extJSON.stringify(new Int32(42));
assert.equal(serialized, '{"$numberInt":"42"}');
serialized =
extJSON.stringify({ _id: { $nin: [ new ObjectID('591801a468f9e7024b6235ea') ] } });
assert.equal(serialized, '{"_id":{"$nin":[{"$oid":"591801a468f9e7024b6235ea"}]}}');
});

it('should correctly throw when passed a non-string to parse', function() {
// Create ExtJSON instance
var extJSON = new ExtJSON();
Expand Down

0 comments on commit 66fe3d9

Please sign in to comment.