Sitemap

Mongoose Nested Paths vs SubDocuments

2 min readMar 13, 2021

--

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:

Press enter or click to view image in full size
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:

Press enter or click to view image in full size
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:

Press enter or click to view image in full size
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:

Press enter or click to view image in full size
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.

--

--

Adam Drake
Adam Drake

Written by Adam Drake

I’m a Frontend Engineer writing about design, performance, and the craft of building great web experiences. Think deeply, build simply.