简体   繁体   English

如何使用JavaScript有条件地将过滤器应用于Firestore查询

[英]How to conditionally apply a filter to a Firestore query with JavaScript

I put in some breaks, and I can see that my if statement is being hit correctly, but the return data is not taking the additional where clause into account. 我稍作休息,可以看到我的if语句被正确命中,但是返回数据没有考虑其他where子句。 Basically if it's the start month I don't want it to have a starting point, and just return any that are not complete. 基本上,如果这是开始月份,我不希望它有一个起点,只返回不完整的月份。 After that I want it to just pull back a month at a time. 之后,我希望它一次只退回一个月。

I've also verified my date values are correct. 我还验证了我的日期值正确。

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)
    })
})

Query objects in Firestore are immutable, meaning they can't be modified after being created. Firestore中的查询对象是不可变的,这意味着它们在创建后无法修改。 What you need to do is build a new query upon a prior query. 您需要做的是在先前查询的基础上建立一个新查询。 For example: 例如:

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)
}

Note here that I'm reassigning search to a new query object built upon the original search. 请注意,我正在将search重新分配给基于原始搜索的新查询对象。 This new search will apply all of the filters at the same time. 此新搜索将同时应用所有过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM