在Firestore查询

时间:2018-04-23 05:26:03

标签: node.js firebase google-cloud-firestore google-cloud-functions es6-promise

我有一个HTTP Cloud功能,可以在Firestore中查询和更新文档。基本上,该功能是从集合中选择所有车辆,计算不同时间范围(24小时,12小时和6小时)的每辆车的能源使用情况,汇总结果并使用结果更新另一个集合。

这就是我的Firestore的结构。

vehicles (collection)
----vehicle (document)
    -----telemetry (subcollection) this is where the energy values will come from

这是我的脚本到目前为止,我使用Promise.all来组合不同时间范围的所有查询,计算每辆车的能源使用情况并将其添加到运行总计中,但这不起作用好。

exports.getAllEnergyUsage = functions.https.onRequest((req, res) => {

  const store = admin.firestore()
  store.collection('vehicles').get().then(snapshot => {

    let allYesterdayResult = 0;
    let allTwelveHourResult = 0;
    let allSixHourResult = 0;

    snapshot.forEach(doc => {
      const data_dict = doc.data();
      let queryResults = [];
      const vehicle = data_dict.vehicle_name;
      const vehicleRef = store.collection('vehicles').doc(vehicle);
      const today = new Date();
      const yesterday = new Date(today.getTime() - (24*60*60*1000));
      const twelveHours = new Date(today.getTime() - (12*60*60*1000));
      const sixHours = new Date(today.getTime() - (6*60*60*1000));

      // console.log(today, sixHours);

      var queries = [
        vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', yesterday).get(),
        vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', twelveHours).get(),
        vehicleRef.collection('telemetry').where('time_stamp', '<', today).where('time_stamp', '>', sixHours).get()
      ]

      for (var i = 0; i < queries.length; i++) {
        queryResults.push(
          queries[i]
        )
      }

      Promise.all(queryResults)
        .then(snapShot=> {

          const yesterdayResult = result => getEnergy(result);
          const twelveHourResult = result => getEnergy(result);
          const sixHourResult = result => getEnergy(result);

          allYesterdayResult += yesterdayResult(snapShot[0])
          allTwelveHourResult += twelveHourResult(snapShot[1])
          allSixHourResult +=sixHourResult(snapShot[2])


          console.log("Done updating vehicle ", vehicle)
          // return res.send({"Result" : "Successful!"})
        }).catch(reason => {
          console.log(reason)
          // return res.send({"Result" : "Error!"})
      });



    })
    var vehicle_summary = {
      yesterday : allYesterdayResult,
      twelveHourResult : allTwelveHourResult,
      sixHourResult : allSixHourResult,
      timestamp : FieldValue.serverTimestamp()

    }
    console.log(vehicle_summary);
    store.collection('vehicles_summary').doc('energy').set(vehicle_summary);
  })

return res.send({"Result" : "Successful!"})


});

这是结果,这不会给我我想要的能量使用的摘要,因为根据我的理解,承诺仍在运行,但功能已经返回(如果我错了,请纠正我)。

RESPONSE RECEIVED FROM FUNCTION: 200, {"Result":"Successful!"}
info: { yesterday: 0,
  twelveHourResult: 0,
  sixHourResult: 0,
  timestamp: FieldValue {} }
info: Running loop on each SnapShot=======
info: Running loop on each SnapShot=======
Running loop on each SnapShot=======
Done updating vehicle  Vehicle2
Running loop on each SnapShot=======
Running loop on each SnapShot=======
info: Running loop on each SnapShot=======
Done updating vehicle  Vehicle1
info: Running loop on each SnapShot=======
info: Running loop on each SnapShot=======
Running loop on each SnapShot=======
info: Done updating vehicle  Vehicle3

知道如何才能实现这一目标吗?我来自Python,只是学习node.js,我仍然在思考同步。

1 个答案:

答案 0 :(得分:0)

您在异步工作的任何完成之前返回结果:

return res.send({"Result" : "Successful!"})

发送此响应后,将终止该功能。无法保证此后的任何异步工作都能按照您的预期完成。

对于HTTP功能,在所有异步工作完全完成后,发送响应