首页 > 解决方案 > 如果一个用户注册了sam,另一个用户也可以注册sam。我怎样才能防止这种情况?

问题描述

我在我的统一项目中使用 firebase firestore。我做了注册部分,但是如果一个用户用sam的名字注册,另一个用户也可以用sam的名字注册。我怎样才能防止这种情况?(我正在使用此代码)

public void SaveUserData()
    {

        DocumentReference docRef = db.Collection("users").Document(uname.text);
        Dictionary<string, object> city = new Dictionary<string, object>
{
            { "name", uname.text },
            { "email", email.text },
            { "password", password.text },
            { "wallet", wallet.text },
            { "uid", auth.CurrentUser.UserId },
            { "score", 0 },
            { "timestamp", FieldValue.ServerTimestamp }
};
        docRef.SetAsync(city).ContinueWithOnMainThread(task => {
            Debug.Log("Added data to the LA document in the cities collection.");
            PlayerPrefs.SetString("currentUname", uname.text);
            SceneManager.LoadScene(1);
        });
    }

标签: c#firebaseunity3dgoogle-cloud-firestore

解决方案


只是为了扩展 derHugo 正确的评论:

您可以通过多种方法实现此目的,第一种方法是 derHugo 所说的,检查是否有任何其他用户包含该名称,类似于:

//Assuming that you are using client SDK and that your User class has a variable name called name
string COL_ID_USERS = "users";
Query usersQuery = db.Collection(COL_ID_USERS).WhereEqualTo(nameof(User.name) ,uname.text);
QuerySnapshot colQuerySnapshot = await usersQuery.GetSnapshotAsync();

if(colQuerySnapshot.Documents.Count() > 0)
{
    //Already exists the user   
}
else
{
    //Collection does not exists or is empty, so no user has this name
}

第二种方法是将所有用户名存储在不同的文档/集合中,因此每次要检查时,而不是查询所有用户,只需在此文档上进行简单搜索,基本上是为了利用非关系数据库的工作原理.


推荐阅读