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:
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:
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.
I then updated the schema to use a subdocument:
My tests started failing. Which was a relief because at least it made sense now! :)
I then updated my register function to:
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.