【问题标题】:How to conditionally apply a filter to a Firestore query with JavaScript如何使用 JavaScript 有条件地将过滤器应用于 Firestore 查询
【发布时间】:2019-02-08 19:29:54
【问题描述】:

我放了一些休息,我可以看到我的 if 语句被正确命中,但返回数据没有考虑额外的 where 子句。基本上,如果它是开始月份,我不希望它有一个起点,而只是返回任何不完整的。在那之后,我希望它一次拉回一个月。

我还验证了我的日期值是正确的。

let endDate = moment(date).add(1, 'M').toDate()
var search = fb.ledgersCollection.where('accountId', '==', this.account.id)
                    .where('completed', '==', false)
                    .where('date', '<', endDate)


if(date != this.startDate) {
    search.where('date', '>', date)
}

search.orderBy('date', 'asc').orderBy('deposit', 'desc').orderBy('name', 'asc').get().then(docs => {

    docs.forEach(doc => {

        let ledger = doc.data()
        ledger.date = new Date(1000* doc.data().date.seconds)
        ledger.id = doc.id
        this.currentBalance = parseFloat(Number(this.currentBalance) + Number(ledger.amount)).toFixed(2)
        ledger.balance = this.currentBalance
        this.ledgerItems.push(ledger)
    })
})

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    Firestore 中的查询对象是不可变的,这意味着它们在创建后无法修改。您需要做的是在先前查询的基础上构建一个新查询。例如:

    var search = fb.ledgersCollection.where('accountId', '==', this.account.id)
                        .where('completed', '==', false)
                        .where('date', '<', endDate)
    
    
    if(date != this.startDate) {
        // build a new query based off the original query
        search = search.where('date', '>', date)
    }
    

    请注意,我将search 重新分配给基于原始搜索构建的新查询对象。此新搜索将同时应用所有过滤器。

    【讨论】:

    • 如此明显。让我感到困惑的总是简单的错误。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2013-06-16
    • 2014-06-04
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多