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.
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"))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加