简体   繁体   中英

Not able to get document snapshot when I pass a variable as document reference

First of all, I am new to asking questions on stack overflow and would like to apologise for any mistakes while asking the question.

I am trying to get some data that I have in firebase firestore in node.js. Here is the code:

firestoreDatabaseName
  .collection("collectionName")
  .doc(request.body.id)
  .get()
  .then((snapshot) => {
    if (snapshot.exists) {
      console.log(request.body.id);
      console.log(snapshot.data());
      response.send("Document found.");
    } else {
      console.log("Document doesn't exist", request.body.id);
      response.send("Document doesn't exist.");
    }
  })
  .catch((err) => {
    console.log(err);
  });

When I run the above code, the result that get's logged into the the console is: "Document doesn't exist 5TLopY8RCHeUZolA0d2v", 5TLopY8RCHeUZolA0d2v being the document reference id which I am passing through the variable "request.body.id". I have checked in the firestore and this document exists. Now when I run the above code by passing the same document reference id as string, I get the snapshot and the data. Here is the code that works:

firestoreDatabaseName
  .collection("collectionName")
  .doc("5TLopY8RCHeUZolA0d2v")
  .get()
  .then((snapshot) => {
    if (snapshot.exists) {
      console.log(snapshot.data());
      response.send("Document found.");
    } else {
      response.send("Document doesn't exist.");
    }
  })
  .catch((err) => {
    console.log(err);
  });

This code is able to log the data to the console successfully while the code above isn't, event though the document reference is same in both cases. Please help.

Ok. I found the solution and it was extremely stupid mistake on my behalf. It seems the id that I was passing as document reference had some white spaces at the end and when I used string.trim() it fixed the issue. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM