Mongoose Nested Paths vs SubDocuments

I am currently working on a project and using mongodb with mongoose. I recently was implementing a new parameter into my schema on a project I was working on and I was faced with the decision about whether to use a ‘Nested Path’ or a ‘Subdocument’.

See the Mongoose documentation for more details.

I decided initially to go with the Nested Path because from what I read it didn’t seem to make much difference which you went with, at least for the parameter I was introducing. All it was going to be was an object with some further parameters to set ‘User Preferences’.

This is what I initially had:

User preferences set on the mongoose schema

This was fine and it was working and all my integration tests were passing.

The Problem I found

However, this way of writing allowed me to introduce a bug into my code. On my user register function I had:

User register function which introduced a bug

As you can see I set the preferences: true and my tests were still passing. How come?! It seemed the schema was ignoring what I wrote here and overrode it with the default schema architecture but I am honestly not sure.

Subdocument

I then updated the schema to use a subdocument:

User preferences using a subdocument approach

My tests started failing. Which was a relief because at least it made sense now! :)

I then updated my register function to:

Updated user register function that was now implemented correctly

And everything started passing. Therefore going forward I will use subdocuments as it seems more logical to me.

Would love to hear if anyone else was facing a similar decision and what was the deciding factor in the choice you made.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Drake

Adam Drake

Father. Husband. Music Lover. Avid Reader. Spiritual Seeker. Czech — Prague. Constantly Failing. But remember… don’t take yourself too seriously.