如何修复 MongoDB Stitch 函数中的“结果未定义”

Ece*_*Ece 5 javascript asynchronous mongodb mongodb-stitch

我在 MongoDB 中创建 Stitch 函数并得到未定义的结果而不是双倍。

我正在开发一个 iOS 应用程序,使用 MongoDB 数据库。我正在创建缝合函数,并使用 callFunction(withName:withArgs:_:) 方法。我编写了一个函数来计算平均早晨值。我想将早上的值返回给应用程序。这是下面的代码。

exports = function(DAY,MONTH){
    var total = 0.0;
    var count = 0.0;
    var morning = 0.0;

    var collection = context.services.get("mongodb-atlas").db("database_name").collection("collection_name");
    var docs = collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0; 
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });
};
Run Code Online (Sandbox Code Playgroud)

“““输出”””

上午 869.5729166666666

结果: { "$undefined": true } 结果 (JavaScript): EJSON.parse('{"$undefined":true}')

"""-输出结束"""

我试图返回双倍的早晨值,但它返回 BSONUndefined。当我尝试从 iOS 应用程序获取结果时,我得到 """ Morning: BSONUndefined() """ 但在 return 语句之前,它会打印早晨值以正确拼接控制台。

小智 0

您没有编写集合,{正在发送 $undefined:true}

解决方案1 ​​返回collection.find结果

return collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0; 
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });
Run Code Online (Sandbox Code Playgroud)

解决方案2:

返回文档本身

var docs = collection.find({month: { $eq: MONTH },
    day: { $eq: DAY },
    hour: { $gte: 8 },
    hour: { $lt: 13 }
    }).toArray().then((data) => {
        data.forEach((el) =>{
            total = total +  el.value;
            count = count + 1.0; 
        });
        morning = total/count;
        console.log("morning");
        console.log(morning);
        return {morning};
    })
    .catch((error) => {
        console.log(error);
        return {morning};
    });

return docs
Run Code Online (Sandbox Code Playgroud)