[英]MongoDB, NodeJS. Get element from promise
I have request to DB with promises, I want to extract 2 values("latitude" and "longitude") for all documents and put it to array.我向 DB 提出了承诺,我想为所有文档提取 2 个值(“纬度”和“经度”)并将其放入数组中。
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.latitude);
console.log(Presults[0].latitude); console.log(Presults[0].latitude);
But I want get output array like this但我想像这样得到 output 数组
[
{ 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);
});
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)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.