You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB查询返回的含locations字段的JSON对象数组转换为二维数组?

How to convert MongoDB query results into a 2D array in Express?

Problem Context

I have a location collection stored in MongoDB, and I've built a simple Express API to fetch this data. Right now, the data returned for result2 is an array of objects each containing a locations field, but I need to convert this into a pure 2D array (just the nested arrays without the parent objects).

Current API Code

app.get('/onlyfields', (req, res) => { 
  const promise1 = onlyfields.find({}, {_id:0}) 
  const promise2 = geopoints.find({}, {locations:1, _id:0}) 
  Promise.all([promise1, promise2]) 
  .then(([result1, result2]) => { 
    res.send({ fields: result1, rows: result2 }) 
    console.log(result2) 
  }) 
  .catch(err => { 
    return res.status(400).json({ error: 'Erorr en STATUS2' }) 
  }) 
})

Current Output (from console.log(result2))

[ 
  { locations: [ 2, '2015-01-15 14:00:41 +00:00', '2015-01-15 14:11:18 +00:00', 1, 1.4, -73.9837265, 40.74634171, -73.96679688, 40.76140594, 8.5, 0, 9.3 ] }, 
  { locations: [ 2, '2015-01-15 14:00:41 +00:00', '2015-01-15 14:11:18 +00:00', 1, 1.4, -73.9837265, 40.74634171, -73.96679688, 40.76140594, 8.5, 0, 9.3 ] } 
]

Desired 2D Array Format

[ 
  [ 2, '2015-01-15 14:00:41 +00:00', '2015-01-15 14:11:18 +00:00', 1, 1.4, -73.9837265, 40.74634171, -73.96679688, 40.76140594, 8.5, 0, 9.3 ] , 
  [ 2, '2015-01-15 14:00:41 +00:00', '2015-01-15 14:11:18 +00:00', 1, 1.4, -73.9837265, 40.74634171, -73.96679688, 40.76140594, 8.5, 0, 9.3 ] 
]

Solution

This is a straightforward fix using JavaScript's Array.map() method to extract the locations array from each object in result2:

app.get('/onlyfields', (req, res) => { 
  const promise1 = onlyfields.find({}, {_id:0}) 
  const promise2 = geopoints.find({}, {locations:1, _id:0}) 
  Promise.all([promise1, promise2]) 
  .then(([result1, result2]) => { 
    // Transform the object array into a pure 2D array
    const transformedRows = result2.map(item => item.locations);
    res.send({ fields: result1, rows: transformedRows }) 
    console.log(transformedRows) // This will now log your desired 2D array
  }) 
  .catch(err => { 
    // Fixed the typo in "Erorr" to "Error" here
    return res.status(400).json({ error: 'Error en STATUS2' }) 
  }) 
})

Quick Notes:

  • If there's a chance some documents might not have the locations field (unlikely given your query projection), you can add a fallback to avoid errors:
    const transformedRows = result2.map(item => item?.locations || []);
    
  • Your query projection {locations:1, _id:0} already ensures each document only includes the locations array and excludes _id, so the map operation is safe for your use case.

内容的提问来源于stack exchange,提问作者Amin Baig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:29:05