我有以下功能:
exports = function () {
const bases = ["02930919000100", "31599354000128", "31588482000176"];
const promises = bases.map(async (value, index) => {
const mongo = context.services.get("mongodb-atlas").db(value);
return mongo.collection("vendas").aggregate([
{
$match: {
data: {
$gte: "2021-10-01",
$lte: "2021-10-29",
}
}
}
]); //Look at this line
})
return Promise.all(promises);
};
你的回报是空的:
[{},{},{}]
但是,如果我将“.toArray()”放在我在代码中注释的行上,则返回有效。
exports = function () {
const bases = ["02930919000100", "31599354000128", "31588482000176"];
const promises = bases.map(async (value, index) => {
const mongo = context.services.get("mongodb-atlas").db(value);
return mongo.collection("vendas").aggregate([
{
$match: {
data: {
$gte: "2021-10-01",
$lte: "2021-10-29",
}
}
}
]).toArray(); //Look at this line
})
return Promise.all(promises);
};
只需放置“.toArray()”即可,返回是:
[[{“_id”:{“$oid”:“615b4b15bbe1278ebc65d8cf”},“id_vendas”:{“$numberInt”:“77588”}}],[{“_id”:{“$oid”:“615b7676bbe1278ebc6fe62e” },“id_vendas”:{“$numberInt”:“127454”}}],[{“_id”:{“$oid”:“615b2105bbe1278ebc5af4be”},“id_vendas”:{“$numberInt”:“61102”} }]]
为什么?根据文档聚合的返回是查询文档(https://docs.mongodb.com/realm/mongodb/actions/collection.aggregate/),我不明白为什么我必须使用“toArray()”在这种情况下。