【问题标题】:Query firestore database on timestamp field在时间戳字段上查询 Firestore 数据库
【发布时间】:2019-04-30 15:22:42
【问题描述】:

我对 firestore(和编程)比较陌生,无法在线找到解决问题的方法。

希望查询现有集合中的文档。文档都有时间戳字段。

当我现在尝试查询所有文档“>”或“”或“

这些按预期返回的文档:

var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '<', today).get().then(function(querySnapshot) {

这些不会返回任何内容:

var today = new Date()-604800000;
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

var today = new Date();
db.collection("****").where('display', '==', true).where('createdAt', '>', today-604800000).get().then(function(querySnapshot) {

只是为了它的见鬼

var today = new Date()-1;
db.collection("****").where('display', '==', true).where('createdAt', '>', today).get().then(function(querySnapshot) {

我看到其他人要求查看 Firestore 中该字段的外观,所以这是一张图片: sorry it's a link

如果还有其他可能有用的信息,请告诉我。谢谢!

编辑以显示下一次尝试:

var config = {****};
firebase.initializeApp(config);

const db = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
db.settings(settings);

var today = new Date();
var yesterday = date.setDate(today.getDate() - 1);
db.collection("****")
    .where('display', '==', true)
    .where('createdAt', '>', yesterday)
    .get()
    .then(function(querySnapshot) {console.log(createdAt)});

【问题讨论】:

  • 你确定日期对象代表“7天前”吗?
  • 此时,我只是想让它过滤,所以我不确定实际数字是否重要。绝对尝试过其他数字。当我修改后显示今天的变量时,它显示正确。
  • 不能使用数字进行过滤,您应该使用Date 对象进行过滤。而且您必须确保您的数据库中有比“7 天前”更早的记录,并且传递的日期对象表示“7 天前”,对吧?
  • 好的,所以不使用数字进行过滤。我会记住的,谢谢。绝对检查了数据库,并且有记录可以追溯到一段时间。还为将来添加了一些内容,以检查事情是否朝着那个方向发展。我是否在这里错误地创建了日期对象 var today = new Date()-604800000?

标签: firebase google-cloud-firestore


【解决方案1】:

好的。所以我从一位非常有帮助的谷歌开发者那里得到了一些帮助。

这最终奏效了。

var beginningDate = Date.now() - 604800000;
var beginningDateObject = new Date(beginningDate);

db.collection("****")
    .where('display', '==', true)
    .where('createdAt', '>', beginningDateObject)
    .get()
    .then(function(querySnapshot) {console.log(/* ... */)});

【讨论】:

猜你喜欢
  • 2020-01-26
  • 2019-02-20
  • 2020-10-11
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 2021-06-14
相关资源
最近更新 更多