1

I'm having a problem trying to insert an object inside a multiple nested array in my mongoose schema for mongoDB. I have the following structure:

{
    contries: [{
        name: 'String',
        states: [{
            name: 'String',
            cities: [{
                name: 'String',
                regions: [{
                    name: 'String',
                    habitants: [{
                            name: 'String',
                            age: Number
                        },
                        {
                            name: 'String',
                            age: Number
                        }
                    ]
                }]
            }]
        }]
    }]
}

1 - Imagine I want to insert habitants inside a specific region in a specific city and so on, how can I build the query?

2 - If a recieve this entire json object as a request, I need to check if any of the country, city, state or region exist, if none of them exist, I need to create and insert the habitants in the array.

3 - If I need to get only the habitants array from one specific region in a specific city, how can I use projection operator to filter this? (I want mongo to filter, not the application).

4(BONUS) - Habitants array only contain the object Id of a habitant object, just need to use populate?

1

1 Answer 1

1

Its not possible to do these things with mongodb.
According to mongodb docs its not possible to travers more then 1 dept in arrays.

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value.

However you can use another schema like:
Bring the Habitant doc to top level
This is a Habitant doc:

{
  name: 'hab1',
  country: 'country1',
  city: 'cit1',
  region: 'region1'
}

With this schema You can normalize or denormalize data and can query and project data easily.

UPDATE: This mongodb limitation seems to resolve in the near future https://jira.mongodb.org/browse/SERVER-27089

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, I shall change my Schema, thanks @kailniris

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.