[英]How to check if Firestore query is empty or document that I am trying to fetch does not exist?
I am trying to fetch a document in Cloud Firestore based on a field ID, but that ID cannot be found, how to check that because it is throwing an error?我正在尝试根据字段 ID 在 Cloud Firestore 中获取文档,但找不到该 ID,如何检查是否因为它引发错误?
getMenu = () => {
try {
this.setState({
loading_menu: true
})
var ref = firebase.firestore().collection('restaurants_menu')
.where("rest_id", "==", this.getSelected.rest_id)
.limit(this.state.limit_menu)
ref.onSnapshot((querySnapshot => {
var menu = querySnapshot.docs.map(doc => { return { ...doc.data(), id: doc.id } });
var lastVisibleMenu = menu[menu.length - 1].rest_id;
this.setState({
menu: menu,
lastVisibleMenu: lastVisibleMenu,
loading_menu: false,
});
}));
}
catch (error) {
console.log("SOMETHING HAPPENED, WE COULD NOT FETCH restaurants_menu: ", error);
}
}
If your snapshot handler is getting invoked, then there was no error.如果您的快照处理程序被调用,则没有错误。 Just check the length of the querySnapshot.docs
array to find out how many documents were matched by the query.只需检查querySnapshot.docs
数组的长度即可找出查询匹配了多少文档。 It's not an error to match 0 documents - you should expect that could be the case.匹配 0 个文档不是错误 - 您应该预料到可能是这种情况。
If you want to handle possible errors, you should be passing more than a single snapshot handler.如果您想处理可能的错误,您应该传递多个快照处理程序。 The documentation for onSnapshot() suggests that you should pass a single observer object with various properties for each type of handler function. onSnapshot()的文档建议您应该为每种类型的处理程序函数传递具有各种属性的单个观察者对象。
ref.onSnapshot({
next: snapshot => {
// your snapshot handler code
},
error: error => {
// your error handling code
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.