猫鼬在数组中查找元素 [英] Mongoose find element in array
问题描述
我刚开始使用猫鼬,遇到了寻找元素的问题...
I just started with Mongoose and having issues finding elements...
我的模式包含一个subregions
数组,我想通过其code
从中找到匹配的数组.该架构如下:
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
}
}]
...
};
我想出了
find({
subRegions: {
"$in": [{
code: regionCode
}]
}
}).exec(...)
但这不起作用...
推荐答案
您的术语不正确,因为该结构不是多维"数组,因为这些结构具有数组中的数组",因此具有维度".这只是数组中的对象".
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.
因此,您的问题是一个基本情况,即错误地处理了参数.您不需要 $in
来搜索数组,而是需要将参数的列表/数组"应用于该字段.
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(...);
您基本上只需要$in
来满足$or
条件,便可以查找subRegions.code
的替代值,因此当只有一个值要匹配时就不需要它.
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.
这篇关于猫鼬在数组中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!