【问题标题】:Firestore request with filter on timestamp property does not work带有时间戳属性过滤器的 Firestore 请求不起作用
【发布时间】:2021-01-21 11:22:36
【问题描述】:

我想使用本地节点脚本在 Firestore 上执行临时请求:

const firebase = require("firebase");
require("firebase/firestore");

firebase.initializeApp({
    apiKey: 'XXX',
    authDomain: 'XXX',
    projectId: 'XXX'
});

var db = firebase.firestore();

async function main() {
    var startTime = Date.parse('2020-09-03T12:56:00.000+02:00') / 1000;
    console.log('startTime = ', startTime)

    const ordersRef = db.collection('orders');
    const snapshot = await ordersRef
        // .where('uuid', '==', 'b4543f28-11c9-4aa5-b7c1-fabd344d5e4a')
        .where('created', '>=', startTime)
        .get();

    if (snapshot.empty) {
        console.log('No matching documents.');
        return;
    }

    snapshot.forEach(doc => {
        console.log("%j", doc.data());
    });
}

main()
    .then(text => {
        console.log('finished');
    })
    .catch(err => {
        console.log('error');
    });

当我使用条件.where('uuid', '==', 'b4543f28-11c9-4aa5-b7c1-fabd344d5e4a') 执行请求时,我得到了预期的响应:

➜  ~/Projects/firestore  node adhoc.js
startTime =  1600356360
{"bid":"NhsrIsu8OLRqO80xfZmS","valid":true,"uuid":"b4543f28-11c9-4aa5-b7c1-fabd344d5e4a","created":{"seconds":1599130708,"nanoseconds":412000000}, ...}
finished

但是当我使用.where('created', '>=', startTime) 执行请求时(意思是:仅此 where 子句),它以某种方式失败(未找到文档),但我知道应该有多个结果..

➜  ~/Projects/firestore  node adhoc.js
startTime =  1600356360
No matching documents.
finished

你能告诉我我做错了什么吗?谢谢!

[更新]

下面是时间戳值的截图:

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    Firestore 具有特殊的时间戳类型。

    https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

    你有两个选择:

    • 将created 字段设为类型号,其中包含值1600356360。我有时这样做是为了避免对 firebase 类型的依赖。
    • 使用Date 对象进行比较。无需转换。 var startTime = Date.parse('2020-09-03T12:56:00.000+02:00');

    【讨论】:

    • 这个答案可能会有所帮助。 stackoverflow.com/questions/47000854/…
    • 效果很好,谢谢.. 不知道为什么我想将日期转换为 int.. 如果这对下一个遇到此问题的人有帮助,语法如下:@987654327 @
    猜你喜欢
    • 2020-02-28
    • 2021-07-07
    • 2015-10-15
    • 2023-04-09
    • 2018-09-29
    • 2022-06-11
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多