Mongoose find element in array

别说谁变了你拦得住时间么 提交于 2019-12-12 19:15:17

问题


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:


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.



来源:https://stackoverflow.com/questions/35214194/mongoose-find-element-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!