Default value for nested arrays

Good day,

is it possible in MongoDB to have default values in nested arrays or objects?

I use the following schema for a nested object:

However, when I retrieve this schema on the frontend, with “findOne”, “used” does not have a default value at all:

nested_02

I would like to prepopulate this array with a default value, if it is empty, to access it with the JS frontend without always checking if this array exists.

Do you have any idea how I could achieve this, or if this would even be a good practice concerning data modelling?

Thank you!

Best regards

Hi @Malte_Hoch

is it possible in MongoDB to have default values in nested arrays or objects?

No, since MongoDB is a flexible schema database, it cannot assume that the structure of one document will be mirrored by another document, even in the same collection.

Do you have any idea how I could achieve this, or if this would even be a good practice concerning data modelling?

Having said that, some ODMs like Mongoose do allow you to define schemas and default values for a collection. See Mongoose defaults for example.

Regarding data modeling, generally you design your schema according to how the data would be used instead of how they will be stored, so you would want your schema to be easy to query. If your nested array structure proves to be difficult to query, then you might want to revisit the schema design.

You might also might to check out the MongoDB University course M320: Data modeling, but please note that this course assumes you’re somewhat familiar with basic MongoDB concepts already.

Best regards
Kevin

Hi @kevinadi

Thank you for your prompt and detailed reply. That makes definitely sense to me according your explanation!

JavaScript in the frontend cannot do anything with an empty nested array. You could, of course, in the frontend either use ternary operators for each array, which blows up the code a bit, or send an empty nested array from the backend by checking if this nested array has any values.

As you said: In the schema you only specify how the data set can and may look.

The latter would be my current solution. Still not sure if this approach is a good style.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.