← back to the index

Mongoose and types, you got me

I have been using NodeJS for a while now and once in a while I hit this random bug where I could not add any properties to a javascript object. I managed to tinker my way around it -- but today while working on something else I finally figured out my issue and it was so stupid it made me angry -- well not really but angry enough to write this post.

This all comes back to Javascript and it type checking or lack thereof.


Mongoose is a great object modeler for NodeJS -- saves us countless hours of writing the same boilerplate code which we would inadvertently litter with typos and bugs.

The process is simple, define a model, save that model, then finally call that model get an object.

There is one caveat which was not clear to me which is now. That onject when it comes back is not JSON.

Seems pretty dumb when I type that because JSON != Object

When the Mongoose object was coming back I was treating it like JSON, trying to just add another property into it. The end result was a silent error and one fustrated developer.

The fix is simple, just convert the object to JSON, but be fore warned any functions inside that Mongoose objects will be discarded.

var dataThinggy = mongooseObject.toJSON();

In a future version of Javascript we may be required to be setting the "type casting" of data we expect to be storing in an variable, and the legions of developers may take up pitchforks and revolt, but I would have those 2 hours of my life back.