如何将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
locationsfield (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 thelocationsarray and excludes_id, so the map operation is safe for your use case.
内容的提问来源于stack exchange,提问作者Amin Baig
相关产品推荐
相关产品推荐

