将猫鼬find()查询结果转换为平面数组

时间:2018-07-14 08:00:27

标签: mongodb mongoose

在猫鼬的find()查询中,我得到的结果是:

[
   {
      "services":[
         {
            "location":[
               17.4374614,
               78.4482878
            ]
         },
         {
            "location":[
               17.4020637,
               78.48400519999996
            ]
         },
         {
            "location":[
               17.387031788259197,
               78.47838450137715
            ]
         }
      ]
   }
]

是否有任何方法可以提取输出,使得我只需要一个位置值的数组,例如:-

[
    '17.4374614',
    '78.4482878',
    '17.4020637',
    '78.48400519999996',
    '17.387031788259197',
    '78.47838450137715'
]

编辑:我知道map方法可以完成这项工作,但是我无法找到解决上述查询的map方法的方法。

我的模式:

var serviceSchema = new mongoose.Schema({

  location:[{type: Number}]

})

1 个答案:

答案 0 :(得分:0)

我使用了for-of循环和map函数来获得所需的结果

var your_output =[
                   {
                      "services":[
                         {
                            "location":[
                               17.4374614,
                               78.4482878
                            ]
                         },
                         {
                            "location":[
                               17.4020637,
                               78.48400519999996
                            ]
                         },
                         {
                            "location":[
                               17.387031788259197,
                               78.47838450137715
                            ]
                         }
                      ]
                   }
                ]

var location_array = []
   for (var services of output[0].services) {
      for(var loc of services.location){
         location_array.push(loc)
      }
   }
location_array.map(String)