Need help searching for a value in firestore

≯℡__Kan透↙ 提交于 2021-02-05 10:44:05

问题


I'm new to firestore and I'm making a register page with vue. Before a new user is made, it has to check if the given username already exists or not and if not, make a new user.

I can add a new user to the database, but I don't know how to check if the username already exists or not. I tried a lot of things and this is the closest I've gotten:

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

Anyone got any ideas?


回答1:


Link to documentation: https://firebase.google.com/docs/firestore/query-data/queries#simple_queries

You can where this query, which is beneficial to you in multiple ways:

1: Fewer docs pulled back = fewer reads = lower cost to you.

2: Less work on the client side = better performance.

So how do we where it? Easy.

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 
           });



来源:https://stackoverflow.com/questions/60341540/need-help-searching-for-a-value-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!