3

I just started with Mongoose and having issues finding elements...

My schema contains an array of subregions from which I want to find the matching one by its code. The schema is the following:

 var schema = {
        name: {
            type: String,
            required: true
        }

        ...

        subRegions: [{
            name: {
                type: String,
                required: true
            },
            code: {
                type: String,
                required: true
            }
        }]

        ...

    };

I came up with

find({
    subRegions: {
        "$in": [{
            code: regionCode
        }]
    }
}).exec(...)

but this is not working...

1 Answer 1

9

Your terminology is off as that structure is not a "multi-dimensional" array, since those have "arrays within arrays", hence "dimensions". This is just "objects" within an array.

So your problem here is a basic case of having the arguments the wrong way around. You don't need $in just to search an array, but rather it takes a "list/array" of arguments to apply to the field.

In short, just lookup the field, and use "dot notation":

.find({ "subRegions.code": regionCode }).exec(...);

You would only need $in for essentially an $or condition, looking up alternate values for subRegions.code, so you don't need that when there is only one value to match.

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

2 Comments

Thank you. Yes this is it. It was late and I mixed things up as I initially had ObjectId()s in that array...
THANKS!! You save my day

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.