Home > Software engineering >  Quasar Firestore field equality query filter doesn't work
Quasar Firestore field equality query filter doesn't work

Time:10-13

I am using quasar to read/write unique data to Cloud Firestore but the following code doesn't work. It fails to detect existing record based on the title field. I am using the Web Version 9 syntax.

<script>
import seedData from "../../data/todos.json";
import {
  getFirestore,
  collection,
  getDocs,
  addDoc,
  query,
  where,
} from "firebase/firestore";

const db = getFirestore();
seedData.forEach(async (todo) => {
    console.log("Processing ", todo.title, "...");
    const q = query(
        collection(db, "todos"),
        where("title", "==", todo.title)
    );
    const querySnapshot = await getDocs(q);
    if (querySnapshot.empty) {
        console.log("Add missing todo: ", todo.title);
        await addDoc(collection(db, "todos"), { todo });
        this.todos.push(todo);
    } else {
        console.log("Skip existing record: ", querySnapshot.docs[0].data());
    }
});
</script>

Sample data:

[{
    "userId": 1,
    "id": 1,
    "title": "Learn Quasar", 
    "completed": false
 },
 {
    "userId": 1,
    "id": 2,
    "title": "Learn Vue", 
    "completed": false
 },
 {
    "userId": 1,
    "id": 3,
    "title": "Learn Firebase", 
    "completed": false
 }
]

Any advice and insight is appreciated.

Duplicate data seen at the browser in quasar dev debug session: enter image description here

Duplicate data seen at the Firestore console: Cloud Firestore console

Repo: https://github.com/khteh/quasar

Deployed: https://khteh.github.io/#/firestore

CodePudding user response:

I am unable to reproduce the problem with this simplified code:

const q = query(
  collection(db, "69534155"),
  where("title", "==", "Learn Quasar")
);
const querySnapshot = await getDocs(q);
if (querySnapshot.empty) {
  console.log("Add missing todo: ", "Learn Quasar");
} else {
  console.log("Skip existing record: ", querySnapshot.docs[0].data());
}

For the full working code, see: https://jsbin.com/gekuqec/3/edit?html,console

This prints:

Skip existing record: ...

While when I change the title to something non-existing it prints:

Add missing todo:

I recommend stepping through the code in a debugger, and checking whether todo.title really has the value that exists in your documents.

If you still have the problem after this, try reproducing it in a similar minimal setup as I've shared here, so that we can have a look at that.

CodePudding user response:

Remember to include the full path to the field used for filter <object>.<field>. In this case, it is todo.title. So, where("todo.title", "==", todo.title) fixes the problem.

  • Related