0

Is there a way to modify a Firestore query?

When I use the code below the query will ignore the startAfter

let query = firestore.collection('results')
.where('groupId', '==', req.query.groupId)
.where('seasonInfo.roundId', '==', req.query.roundId)
.orderBy('results.totalPoints', 'desc')
.orderBy('lastPick', 'asc')

if (req.query.lastPoints && req.query.lastDate) {
    query.startAfter(parseInt(req.query.lastPoints), req.query.lastDate) 
}
const pickDocs = await query.limit(10).get()

So I have to write the whole thing in order to make it work.

let query = firestore.collection('results')
.where('groupId', '==', req.query.groupId)
.where('seasonInfo.roundId', '==', req.query.roundId)
.orderBy('results.totalPoints', 'desc')
.orderBy('lastPick', 'asc')

if (req.query.lastPoints && req.query.lastDate) {
    query = firestore.collection('results')
    .where('groupId', '==', req.query.groupId)
    .where('seasonInfo.roundId', '==', req.query.roundId)
    .orderBy('results.totalPoints', 'desc')
    .orderBy('lastPick', 'asc')
    .startAfter(parseInt(req.query.lastPoints), req.query.lastDate) 
}
const pickDocs = await query.limit(10).get()

Is it possible to modify a query without re-entering all data?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Chamanhm
  • 1,060
  • 1
  • 11
  • 17

1 Answers1

2

No, it's not possible. Query objects are immutable. Once you build a query object by calling a series of methods, you can't "undo" those changes later. You have to use your second method to conditionally add filters and ordering if you want them to apply.

If you want a more clear pattern to conditionally apply constraints to a query, see this: Firestore: Multiple conditional where clauses

Basically, you will conditionally apply constraints by reassigning the query object conditionally as needed:

let query = ...
if (someCondition) {
    query = query.startAfter(...)
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441