【问题标题】:Need help searching for a value in firestore需要帮助在 Firestore 中搜索值
【发布时间】:2020-06-06 01:17:42
【问题描述】:

我是 firestore 新手,我正在使用 vue 创建一个注册页面。 在创建新用户之前,它必须检查给定的用户名是否已经存在,如果不存在,则创建一个新用户。

我可以在数据库中添加一个新用户,但我不知道如何检查用户名是否已经存在。我尝试了很多东西,这是我得到的最接近的:

db.collection("Users")
           .get()
           .then(querySnapshot => {
             querySnapshot.forEach(doc => {
               if (this.username === doc.data().username) {
                 usernameExist = true;                              
               }
             });
           });

有人有什么想法吗?

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    文档链接: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 
               });
    
    

    【讨论】:

    • 您可以将循环和if检查替换为更简单的if (!querySnapshot.empty) { usernameExists = true }。
    • 这是一个非常好的建议。我将用它来更新我的答案。谢谢!
    猜你喜欢
    • 2019-03-13
    • 2014-05-20
    • 2012-08-25
    • 2017-08-03
    • 2020-08-03
    • 2017-03-30
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多