首页 > 解决方案 > 使用 Express/Node 编写的嵌套 Google DataStore 查询未获取预期数据

问题描述

我正在尝试datastoreNode/express. 父查询是对 a 的简单get请求,kind子查询将根据上面获取kind的父kind结果的特定列值聚合 other 的特定列。请检查下面的代码以获得更好的洞察力。

app.get("/api/venues/", (req, res, next) => {
  const query = datastore
  .createQuery('venue');

  // parent query run here
  query.run().then(([venuesList]) => {
  venuesList.forEach(
    venue => {
      startDate = moment(new Date()).format('L');
      endDate = moment(new Date()).startOf('week').format('L');
      const queryVenueInvoice = datastore
      .createQuery('invoices')
      .filter('targetacntkey', '=', venue.userid);

      // child query run here
      queryVenueInvoice.run().then(([invoicesList]) => {
        const filteredInvoiceList = invoicesList.filter( invoice =>
          (new Date(invoice.timestamp).toISOString().split('T')[0])
          <= startDate && (new Date(i.timestamp).toISOString().split('T')[0]) >= (endDate));

          venue['weeklySummary'] = filteredInvoiceList.reduce((sum, invoice) => {
            return sum + invoice.totalamount; }, 0);
        })

      venue['venueKey'] = venue[datastore.KEY]
    }
    );
  // venuesList.forEach(venue => console.log(venue));
  res.status(200).json(
    {
      message: "Request was processed successfully!",
      venues: venuesList
    }
  );
})
})

我能够以venuesList填充有venueKey. 但是我无法weeklySummary在响应中看到聚合属性。我在这里想念什么?有人指导我看看预期的结果吗?

标签: javascriptnode.jsexpressgoogle-cloud-datastore

解决方案


看起来您正在尝试在您的场所列表.forEach() 中执行异步操作

所以响应是在那些完成之前发送的。您将需要使用类似的东西

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

app.get("/api/venues/", (req, res, next) => {
  const query = datastore
  .createQuery('venue');

    query.run().then(async ([venuesList]) => {
      await asyncForEach(venuesList, async(venue) => {
        startDate = moment(new Date()).format('L');
        endDate = moment(new Date()).startOf('week').format('L');
        const queryVenueInvoice = datastore
          .createQuery('invoices')
          .filter('targetacntkey', '=', venue.userid);

        // child query run here
        await queryVenueInvoice.run().then(([invoicesList]) => {...

此外,我会将 res.status(200)... 放在 query.run().then(... 和 asyncForEach(... 之外)... 我希望这会有所帮助


推荐阅读