Node.js 无法将Mongoose查找结果转换为数组

Node.js 无法将Mongoose查找结果转换为数组,node.js,mongodb,mongoose,handlebars.js,Node.js,Mongodb,Mongoose,Handlebars.js,我希望将此代码的结果转换为数组 >User .find() .select("-_id services.location ") .lean() .exec(function(err,users){ if (err) { console.log("Error Finding the users") } else { users=JSON.stringify(users); console.log("new:-",

我希望将此代码的结果转换为数组

>User
  .find()
  .select("-_id services.location ")
  .lean()
  .exec(function(err,users){

    if (err) {

      console.log("Error Finding the users")

    } else {

      users=JSON.stringify(users);

      console.log("new:-",users)

      console.log(users)

      res.render('allroads1',{users:users})

    }

   })
我得到的结果是:-

    [{"services":[{"location":[17.4374614,78.4482878]},{"location": [17.4020637,78.48400519999996]}]}]
我希望结果的格式为:-

    [
      "17.4374614",
      "78.4482878",
      "17.4020637",
      "78.484005199996"
    ]

我的模式类似于数字数组:-位置:[{type:Number}]。我使用车把作为我的模板引擎##

如果您将初始响应格式化为数组,那么下面的代码应该可以帮助您完成所需的操作,基本上我们使用map来获取值,然后concat和reduce来展平数组

var x = [[{"services":[{"location":[17.4374614,78.4482878]},{"location": [17.4020637,78.48400519999996]}]}]
        ,[{"services":[{"location":[17.4374614,78.4482878]},{"location":[17.4020637,78.48400519999996]}]}]
].map(function(obj) {
    return obj[0]['services'].map(function(obj){
        return obj['location']
    });
}).reduce(function(acc, val){
    return acc.concat(val);
}).reduce(function(acc, val) {
    return acc.concat(val);
});
console.log(x);
给予

[ 17.4374614,
  78.4482878,
  17.4020637,
  78.48400519999996,
  17.4374614,
  78.4482878,
  17.4020637,
  78.48400519999996 ]
因此,如果不使用reduce和concatenate:

var x = [[{"services":[{"location":[17.4374614,78.4482878]},{"location": [17.4020637,78.48400519999996]}]}]
        ,[{"services":[{"location":[17.4374614,78.4482878]},{"location":[17.4020637,78.48400519999996]}]}]
].map(function(obj) {
    return obj[0]['services'].map(function(obj){
        return obj['location']
    });
});
console.log(x);
你得到

[ [ [ 17.4374614, 78.4482878 ],
    [ 17.4020637, 78.48400519999996 ] ],
  [ [ 17.4374614, 78.4482878 ],
    [ 17.4020637, 78.48400519999996 ] ] ]

对于两个对象数组等,您得到的响应非常混乱,但是使用map从数组中取出对象,而且由于还有一个大小为1的数组,因此obj[0]

我不确定您是否可以。为什么不使用NodeJS并循环响应来创建所需的输出数组呢?能否提供一个更清晰的所需格式示例?我看不到从您的结果和目标结果中获得的方法。@NickCaruso您能指导我如何使用NodeJS循环它们吗?是的。这是可行的,但是,我的数据库中有很多位置对,有没有办法有效地循环它们,而不是将它们硬编码到变量x中。