Tho*_*ysa 5 dart firebase flutter google-cloud-firestore
我在 cloud firestore 中有一个集合,其中包含许多文档,这些文档具有文档创建时间的时间戳值,以及更多信息。我正在经历一些非常奇怪的行为,我无法理解。
我想要做的是:
我有这些疑问:
var snapshotNow = await Firestore.instance
.collection(stationName)
.orderBy('servertime', descending: true)
.limit(1)
.snapshots()
.first;
Run Code Online (Sandbox Code Playgroud)
并查找 1 小时前,依此类推:
var dateTime = DateTime.now().subtract(duration);
Run Code Online (Sandbox Code Playgroud)
并从 1 小时前检索文档:
var snapshotThen = await Firestore.instance
.collection(stationName)
.where('servertime', isGreaterThan: dateTime)
.orderBy('servertime', descending: false)
.limit(1)
.snapshots()
.first;
Run Code Online (Sandbox Code Playgroud)
出于某种原因,这两个截然不同的查询每次都检索相同的文档。即:我从两个查询中获取集合中的最新文档。
我试图做几件事来找出问题所在:
1) 不查看日期,通过删除.where查询中的 。这应该snapshotThen成为集合中最旧的文档。我实际收到的是收藏中的最新文件。这意味着在升序和降序排序时,返回的文档与第一个文档相同。
2) 将限制增加到 1 个以上的文档。当将限制从limit(1)增加到 时limit(10)。对于升序,这始终返回最新的 10 个文档(如预期)。对于 orderBy 降序,发生了一些奇怪的事情。我希望它从集合中返回最旧的 10 个文档。它返回的是两件事之一;1) 10 个最新文档,从最旧到最新排序,或 2) 仅最新文档(不是 10 个文档的列表,而是只有 1 个文档的列表)。
非常感谢任何帮助,我已经为此工作了很长时间,但我无法解决问题所在。我觉得最令人沮丧的是行为发生了变化;有时我只得到 1 个文档,有时我得到 10 个文档,所有文档都使用相同的查询。
从我的角度来看,问题在于 Firestore 时间戳的格式。
Firestore 时间戳示例如下:
Timestamp { _seconds: 1575888466, _nanoseconds: 725000000 }
Run Code Online (Sandbox Code Playgroud)
我已经复制了您所描述的内容,并且使用它效果很好Firestore.Timestamp
您可以使用Firestore.Timestamp.now()Firestore 时间戳格式 和 来获取当前时间Firestore.Timestamp.fromMillis(Date.now()-[MS]),其中 [MS] 是您要减去的时间(以毫秒为单位)。
1 小时 = 3600000 毫秒
1 天 = 86400000 毫秒
因此,示例如下:(我正在使用 Node.js)
let postsRef = db.collection('dates');
const hour= 3600000;
const fullday= 86400000;
var firenow = Firestore.Timestamp.now()
var firepast = Firestore.Timestamp.fromMillis(Date.now()-fullday);
var range1 = postsRef.where("time", ">=", firepast).where("time", "<=", firenow);
let query1 = range1.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
Run Code Online (Sandbox Code Playgroud)
上面将为您提供过去一小时内带有时间戳的文档,替换hour为fullday将为您提供最后 24 小时。
| 归档时间: |
|
| 查看次数: |
1983 次 |
| 最近记录: |