1

I know this might be a duplicate of Firestore: how to perform a query with inequality / not equals but I really did not get an answer I want from that question.

Firestore doesn't accept the inequality operator !=.

Suppose I want to query tasks that are not mine by uid. Querying for the tasks I created is easy since I only need to use ==.

I have the following code.

export default function fetchTasks () {
  return async (dispatch) => {
    const tasks = await db.collection('tasks')
      .where('owner', '>', `/users/${uid}`)
      .where('owner', '<', `/users/${uid}`)
      .get()

    const taskList = []
    tasks.forEach((task) => {
      taskList.push(task.data())
    })

    dispatch({
      type: 'FETCH_TASKS_FULFILLED',
      payload: taskList
    })
  }
}

I can't seem to get this work. Any suggestions would be greatly appreciated. Thanks!

nrion
  • 4,258
  • 4
  • 17
  • 33

1 Answers1

2

Update Sep 2020: v7.21.0 introduced support for not equals (!=) queries! That means you can simply do:

const tasks = await db.collection('tasks')
      .where('owner', '!=', `/users/${uid}`)
      .get();

Original Answer

The answer from Doug to that questions says that you'll need to use two separate queries to get the results: one for db.collection('tasks').where('owner', '>', `/users/${uid}`) and one for db.collection('tasks').where('owner', '<', `/users/${uid}`). You'll then need to merge the results in your client-side code.

So:

const tasks = await db.collection('tasks')
  .where('owner', '<', `/users/${uid}`)
  .get()

let taskList = []
tasks.forEach((task) => {
  taskList.push(task.data())
})

tasks = await db.collection('tasks')
  .where('owner', '>', `/users/${uid}`)
  .get()
tasks.forEach((task) => {
  taskList.push(task.data())
})

dispatch({
  type: 'FETCH_TASKS_FULFILLED',
  payload: taskList
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you. that worked! i thought a compound query would do it, but to no avail. one minor thing though is that you forgot to replace `const` with `let` but other than that, everything works great! – nrion Apr 02 '18 at 14:33
  • How to make sure we use limit filter while doing this? My collection has lot of documents and doing this way may bloat it up. – Ayyappa Oct 17 '19 at 15:29