Tobias
Tobias

Reputation: 7415

Mongoose find element in array

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...

Upvotes: 3

Views: 13477

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

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.

Upvotes: 9

Related Questions