DEV Community

Cover image for Bootcamping 01: An Unexpected Behavior of Mongoose
Alef Lewitt
Alef Lewitt

Posted on

Bootcamping 01: An Unexpected Behavior of Mongoose

When you’re a student in a bootcamp, you’re introduced to so many new
technologies all at once, and sometimes it can be overwhelming. One approach that I’ve found helpful is to try and identify what each technology is adding. Ask yourself - what problem is this technology coming to solve? Why do we need it in the first place?

The tendency to not ask these questions, may stem from a feeling of professionalism that comes with using a new package or technology. It can seem “cool” or “tech-y” to add new jargon to your toolbox, that this can cloud the true professionalism, which is to ask “why do I actually need this package in my project?” Lugging around an unnecessary package can cause more harm than help when deploying and it’s important to attempt to understand the helpfulness of a given package you plan on using in your project.

In coding bootcamps, when teaching usage of the MongoDB database, it’s common to almost immediately use it with the additional package “Mongoose”. Why? What does this third-party library add to the regular MongoDB?

Besides the basic advantages of rigid schemas and models (see this fantastic article by Jesse Hall, Getting Started with MongoDB & Mongoose), there are some hidden advantages, one of which I recently discovered.

A student of mine was using the findOne method, passing it a query value which was “undefined”, (for example, findOne({username}) where username is undefined and in response he was receiving an actual MongoDB document. I was surprised? The MongoDB documentation clearly states that such a case should in-fact respond with “null”!

The answer I discovered lies in one way that Mongoose is “smarter” than MongoDB. Mongoose, in its attempt to only return documents and avoid returning null, won’t ‘agree’ as it were, to send a request of findOne with an undefined query, and so, behind the scenes, when Mongoose’s findOne method is passed an undefined query value, it doesn’t send that query to MongoDB - it first translates the undefined into an empty object, and in-turn, generates a response of an actual document instead of null.

Food for thought: Is this an advantage or a disadvantage? What are your thoughts?

Happy learning! Stay curious, and please share your thoughts!

Top comments (0)