我正在尝试根据 Firebase 数据库中的一些数据生成每周报告,并为此使用 Firebase 云功能。 时间戳实际上存在于子 Node 中。但是,我无法获取任何数据。
我的数据库结构如下:
{
"threads" : {
"228440-1704-4bba-87d7-27327" : {
"messages" : {
"8c98a76c-4456-4326-8e18-6d036b40bfa4" : {
"time" : 1519997400,
"payload": "someData"
},
"898376c-4456-4326-8e18-6deb4wr0bfa4" : {
"time" : 1517174415302,
"payload": "someData"
}
},
"details" : {
"created_At": 1514134435602
}
}
根据详细信息 Node 获取数据:
我正在尝试获取在我的日期范围内(比如上周)存在 threads/details/created_at
的线程。
根据消息 Node 获取数据: 除此之外,在另一个查询中,我想获取上周的所有消息(在不同线程中)。我想即使在这种情况下我也必须使用以下内容来获取线程:
//fetch threads where message.time exists in last week
我正在使用 Firebase 云函数,我的代码如下:
exports.generateReportFromThreads = functions.https.onRequest((req, res) => {
var ref = admin.database().ref('threads');
var startingTime = new Date('Mon, 25 Dec 1995 13:30:00 GMT').getUnixTime();
var currentDate = new Date('Fri, 2 Mar 2018 13:30:00 GMT').getUnixTime();
return ref.orderByChild('details/created_at').startAt(startingTime).endAt(currentDate).once("value", (threadSnapshot) => {
var numberOfThreads = threadSnapshot.numChildren()
var totalMessages = 0
threadSnapshot.forEach((snapshot) => {
var ref = snapshot.child('messages')
var messagesPerThread = ref.numChildren()
totalMessages = totalMessages + messagesPerThread
res.send(`
<!doctype html>
<html>
<body>
<p>Total number of threads = ${numberOfThreads}</p>
<p>Total messages = ${totalMessages}</p>
</body>
</html>`
);
});
});
我在数据库中应用了索引:
最佳答案
Firebase 数据库查询只能对每个子项下已知路径上的属性进行排序/过滤。
您的结构是/threads/$threadid/messages/$messageid
。您无法跨所有线程运行查询,然后筛选每条消息的时间。您要么必须加载所有消息并在客户端/云功能中进行过滤,要么必须更改数据结构以满足您的需求。
有关此内容的更多信息,请参阅我的回答:Firebase Query Double Nested
关于node.js - Firebase 基于子 Node 的日期范围查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071061/