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.

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Airflow In Windows — Docker

Comprehensive look at Azure Databricks Monitoring & Logging

MSYS2 Build Processes Driving You Crazy?

How To Install Roof Rack On Van | Promaster Roof Rack | Unaka Promaster Roof Rack Brackets | 8020

Unsupervised Learning Project

from fit6 http://ift.tt/2iGNZSd via alanafalk.jimdo.com

Difference between CSM & PSM certification ?

Why every company is a software company

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.

More from Medium

Reuse RabbitMQ connection

ExpressJS routing with Decorators, Dependency Injection and reflect-metadata

Achieving 100% Test Coverage — Node.js Edition

WebSocket development with Typescript from scratch