1

I have a collection of tokens in which each document create with auto id but I store a tokenId in the document and now I want to search a single document which has specific tokenId How can I implement where query in my this code

const docRef = doc(db , "tokens")
const data= await getDoc(docRef);
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

1

First, you should use collection() instead of doc() to create a CollectionReference. Then you can build the required Query using query() with where() as shown below:

import { collection, getDocs, query, where } from "firebase/firestore"

const colRef = collection(db , "tokens")

const qSnap = await getDocs(query(colRef, where("tokenId", "==", "TOKEN_VALUE")));

if (qSnap.size) {
  const data = qSnap.docs[0].data();
} else {
  console.log("No token found")
}

Also checkout:

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • its not working still unable to get data however qSnap gives me a firestore document in the form of Vh object i am unable to populate data from it – Usama Saleem Apr 24 '22 at 10:24
  • @UsamaSaleem qSnap is the querySnapshot... `qSnap.docs[0].data()` contains data of your document is it exists – Dharmaraj Apr 24 '22 at 10:28
  • its docs array is empty but there data present in firestore – Usama Saleem Apr 24 '22 at 10:29
  • @UsamaSaleem can you share a screenshot of your document in that case? Also are you passing correct values where()? `where("tokenId", "==", "TOKEN_VALUE")` tokenId is field name in the document and TOKEN_VALUE should be the value that you are looking for. If no docs are matching then there's some issue with these vaalues – Dharmaraj Apr 24 '22 at 10:30
  • yes but where i can share screenshoot – Usama Saleem Apr 24 '22 at 10:33
  • @UsamaSaleem you can edit your question and add it – Dharmaraj Apr 24 '22 at 10:41