MongoDB, NodeJS. Get element from promise

Viewed 68

I have request to DB with promises, I want to extract 2 values("latitude" and "longitude") for all documents and put it to array.

I'm doing like this;

const promises = [
    dbo.collection("users").find({ name: "Mark" }, { latitude: 1, longitude: 1, _id: 0 }).toArray()
]
Promise.all(promises).then(function (Presults) {
        console.log(Presults);


    }).catch(function (err) {
        console.log(err);
    });

as a result I get all fields, for example: name, gender, latitude, longitude etc. When I try to specify that I want only latitude, longitude, I always get result undefined What I've tried: console.log(Presults.latitude); console.log(Presults[0].latitude);

But I want get output array like this

[
    { lat: -31.563910, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 }
];

I tested without promises, it works:

    dbo.collection("users").find(
    { name: "Mark" },
    { latitude: 1, longitude: 1, _id: 0 }).toArray(function (err, result) {
        if (err) throw err;
        var array1 = [];
        var z = { "lat": result[0].latitude, "lng": result[0].longitude };
        var y = { "lat": result[0].latitude, "lng": result[0].longitude };
        array1.push(z, y);

        console.log(array1);
    });
1 Answers

Try this

Promise.all(promises).then(function (results) {
    const data = results.flatMap(v => v.map(k => ({ lat: k.latitude, lng: k.longitude})))

    console.log(data)
})
Related