我是 firestore 的新手,我正在使用 vue 制作一个注册页面。 在创建新用户之前,必须检查给定的用户名是否已存在,如果不存在,则创建一个新用户。
我可以向数据库添加新用户,但我不知道如何检查用户名是否已存在。我尝试了很多东西,这是我得到的最接近的:
db.collection("Users")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
if (this.username === doc.data().username) {
usernameExist = true;
}
});
});
有人有什么想法吗?
最佳答案
文档链接:https://firebase.google.com/docs/firestore/query-data/queries#simple_queries
您可以where
此查询,这对您有多种好处:
1:撤回的文档越少 = 阅读次数越少 = 您的成本越低。
2:客户端工作量减少=性能更好。
那么我们如何where
呢?简单。
db.collection("Users")
.where("username", "==", this.username)
.get()
.then(querySnapshot => {
//Change suggested by Frank van Puffelen (https://stackoverflow.com/users/209103/frank-van-puffelen)
//querySnapshot.forEach(doc => {
// if (this.username === doc.data().username) {
// usernameExist = true;
// }
//});
usernameExists = !querySnapshot.empty
});
关于javascript - 需要帮助在 firestore 中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60341540/