I have a collection of locations in mongodb, I wrote a simple api to get the locations, following is the 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'
})
})
})
The locations data is stored in result2.
the console.log shows the following response:
MongoDB Connected
[
{
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
]
}
]
I need to modify the result2 data to the following format, whaich is an array of arrays:
[
[
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
]
]
Would appreciate any help. Thanks in advance.
CodePudding user response:
You can simply map each of the result's location
array, e.g.
function flatten(data) {
return data.map(currEntry => currEntry.locations)
}
const data = [
{
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
]
}
];
function flatten(data) {
return data.map(currEntry => currEntry.locations)
}
console.log(flatten(data))