使用Express / Node编写的嵌套Google DataStore查询无法获取预期数据
我想在datastore
中实现嵌套的Node/express
查询。父查询是get
上的简单kind
请求,子查询将根据上面提取的父kind
结果的特定列值聚合其他kind
的特定列。请查看以下代码以获得更好的洞察力。
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
。我在这里失踪了什么?任何人都指导我,所以看到预期的结果?
看起来你正试图在你的场地中做异步操作List.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()中。然后(...和asyncForEach之外...(我希望这会有帮助)