toBSON()?

38 views
Skip to first unread message

Axel Kittenberger

unread,
Apr 24, 2012, 5:56:44 AM4/24/12
to node-mongodb-native
Hi is there some function I can provide that changes the way an object
is serialized? Like toJSON()? Or should toJSON work?

Basically I got an Object prototype called "Path", with their private
variable _path which is an Array. When I save it to the database I
just want _path to be saved.

For classical AJAX commnication I just did this and it worked well.

Path = function() {
Object.defineProperty(this, '_path', {value: ['foo', 'bar]}); //
no enumeration
};

... a lot of custom functions to access _path in a custom systematic
way...

Path.prototype.toJSON = function() {
return this._path;
};

However when storing it in a mongodb, i get only { }, without the
contents of _path I would however expect it to be ['foo', 'bar' ].

For now I just put this around before giving it to insert() to get the
output I want
o = JSON.parse(JSON.stringify(o));
But this isn't very efficient.

christkv

unread,
Apr 24, 2012, 6:32:45 AM4/24/12
to node-mongodb-native
Interesting feature but no at the moment it does no support any
concept such as toBSON

It would create a potential mismatch when you retrieve the object
again for reconstructing the object after retrival as you would have
reconstruct the concept of a private property.

JSON.parse/stringify is incredibly fast by many factors over BSON due
to magic going on in V8. So I would think it will still work much
better and the BSON parser would not have to check for every single
object if it implements toBSON and then handle the additional
overhead.

Axel Kittenberger

unread,
Apr 25, 2012, 4:51:49 AM4/25/12
to node-mong...@googlegroups.com
Strange no one else requested this feature so far.

In case of data structures that ought to have prototypes with utility
methods on them, they need to be reconstructed after reading anyway.
So far with JSON/AJAX I had no problem with that.

Kind regards,
Axel

Aaron Heckmann

unread,
Apr 25, 2012, 7:45:23 PM4/25/12
to node-mong...@googlegroups.com
you can do this with a small api on top of the driver. for example mongoose gets away with this by proxying all update/insert/find etc methods and doing the object wrap/unwrapping in between. 
Reply all
Reply to author
Forward
0 new messages