0

I load data from a file

{
    id: '1081',
    title: "Some Prod",
    type: "tap",
    description: "Some Prod",    
    imageUrl: 'https://storage.googleapis.com/.../tooal.jpg',         
    price: 5.99,
    quantity: "1 unit",
    size: "XL",
    rating: 4 
  }

and the code used is

  return Promise.all(items.map(item => {
      const { id, ...data } = item;
      return db.collection(collectionName)
        .doc(id)
        .set(data);
  }));

Now the search function, gives no results

  const {id} = data;
  const store = admin.firestore();

  const querySnapshot = await store.collection("products")
      .doc(id)
      .get();

  const product = querySnapshot.docs.map((doc) => ({
    ...doc.data(),
    id: doc.id,
  }));

Search from firestore is also not giving the results (0 records found for search) The only types available are Number, String, Boolean, so used string (assuming String can be ' ' or " )

enter image description here

How to make my search work ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kris Swat
  • 788
  • 1
  • 10
  • 39

1 Answers1

0

Your code is not at all performing the query that you want. This code is accessing a single document using its Firestore document ID, not the id field in the document:

  const querySnapshot = await store.collection("products")
      .doc(id)
      .get();

(Also, that code does not return a QuerySnapshot object. It returns a DocumentSnapshot, because there can be only one document in a collection with a particular ID.)

If you want to filter documents on a field (any field, even if it's called id), you need to follow the instructions in the documentation for query filters for that:

  const querySnapshot = await store.collection("products")
      .where("id", "==", id)
      .get();

If you look at your screenshot of the console in your question, you will see that it's actually recommending this to you.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I did try that model before. but chnaged based on - (The first query is looking for an explicit user-set field called 'id', which probably isn't what you want.) - https://stackoverflow.com/questions/47876754/query-firestore-database-for-document-id – Kris Swat Jul 01 '23 at 18:44
  • It's up to you to determine if you want to use a field or the document ID. But as I explained, they are not the same query, nor the same code. – Doug Stevenson Jul 01 '23 at 18:45
  • I understood your point document snapshot. const productDoc = await store.collection("products").doc(idString).get(); and return productDoc.data(). What should I do to run the OOTB firebase query as in screenshot – Kris Swat Jul 01 '23 at 20:59
  • That's what I show in my answer. There is even a link to the documentation. – Doug Stevenson Jul 01 '23 at 21:51
  • sure. I accepted the answer. my question was how to search in cloud firestore using filter? note: I want to search only on id. – Kris Swat Jul 02 '23 at 15:18