Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

javascript - Firebase query does not return anything

I coded a function for sending a query to my database and retrieve the result. But if it does not find anything in the database it returns nothing neither undefined nor null.

For this reason, I can not handle whether the data exists in the database or not.

What is the return value of this function?


Code:

usersRef
  .where("nickname", "==", nickname)
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) =>
      doc.data() ? console.log("a") : console.log("b")
    );// i wrote this line for testing the issue
    querySnapshot.size == 0 ? (flag = true) : (flag = false);
  })
  .catch((err) => console.log("err2"))

If the data exists in the database, it prints a, but if not, it prints nothing, neither a nor b.

I used that code in my React-Native project, it also uses a Firebase Firestore database and usersRef means:

const db = firebase.firestore();
const usersRef = db.collection("Users");

Note: the querySnapshot always return a firebase object in JSON format. The doc parameters in forEach returns an object if it exists in JSON format but, if not, it cannot be handled.

Note 2: I also tried doc.data()== null or doc.data()== undefined or doc.data()== "". But they do not print anything in console.log(). I also tried console.log(doc.data()) and nothing changed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if the data exists in database, it prints a but if it does not exist it prints nothing neither a nor b

That's because you're querying the database and getting back an array. If your array has 1 or more items in it, your .forEach call will iterate through them and execute your ternary expression, resulting in a console log call - either a or b. However, if your array is empty, then .forEach won't have anything to iterate over, and so the function you're passing to it will never be executed.

[].forEach(item => console.log(item)) // nothing
[1].forEach(item => console.log(item)) // 1

So the issue is that your database query is just coming back empty on your Windows box. Check your flag variable or the .size member and you should see whether this is the case:

usersRef
  .where("nickname", "==", nickname)
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) =>
      doc.data() ? console.log("a") : console.log("b")
    );
    querySnapshot.size == 0 ? (flag = true) : (flag = false);
    console.log(querySnapshot.size);
  })
  .catch((err) => console.log("err2"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...