Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从嵌套数组中查找数据?_Javascript_Mongodb_Mongoose - Fatal编程技术网

Javascript 如何从嵌套数组中查找数据?

Javascript 如何从嵌套数组中查找数据?,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我有一个模型: const schema = new mongoose.Schema({ country: { type: String }, code: { type: String }, region: [{ name: { type: String }, city: [{ name: { type: String }, latitude: { type: String }, longitude: { type: String

我有一个模型:

const schema = new mongoose.Schema({
  country: { type: String },
  code: { type: String },
  region: [{
    name: { type: String },
    city: [{
      name: { type: String },
      latitude: { type: String },
      longitude: { type: String },
    }],
  }],
})
我需要获得地区->城市->名称列表(地点名称列表) 在开始时,我尝试了一个查询来获取(数组)城市的列表

并接收以下数据:

然后我搜索我发送查询的区域列表:

Model.findOne({ code: req.params.code }, { region: 1 })
并接收如下数据:

我想得到相同格式的城市名称列表

我的数据样本:

{
  "country": "Estonia",
  "code": "ee",
  "region": [
    {
      "name": "Harjumaa",
      "city": [
        {
          "name": "Aegviidu vald",
          "latitude": "59.27941132",
          "longitude": "25.62571907"
        },
        {
          "name": "Anija vald",
          "latitude": "59.27643967",
          "longitude": "25.48167992"
        }
      ]
    }
  ]
}

$project
带有
$region.city.name
路径将为您提供一个数组,因为您有两个嵌套级别。要修复可用于将最终结果展平为单个数组的问题,请尝试:

Model.aggregate([
    {
        $match: { code: "ee" }
    },
    {
        $project: {
            cityNames: {
                $reduce: {
                    input: "$region.city.name",
                    initialValue: [],
                    in: { $concatArrays: [ "$$this", "$$value" ] }
                }
            }
        }
    }
])

你能提供样品吗data@AshayMandwarya添加到正文中
Model.aggregate([
    {
        $match: { code: "ee" }
    },
    {
        $project: {
            cityNames: {
                $reduce: {
                    input: "$region.city.name",
                    initialValue: [],
                    in: { $concatArrays: [ "$$this", "$$value" ] }
                }
            }
        }
    }
])