简体   繁体   中英

Firebase search for users with same username/ database structure

The structure of my database has users with a username that is created when a user creates an account. The username is under the meta data. I already have over 2000 users and never thought to restrict usernames/ make sure not duplicates or append numbers when people login with facebook or google (I am currently just using their names in those cases). I want to be able to search for usernames:

  "Users" : {
    "eOhY4Wp6QNUtEjVTdmBff8UDY5p2" : {
      "meta" : {
        "username" : "testName"
      }
    }
  }

I figured the only way would be to create another section that lists usernames in reverse:

"UserList" : {
        "testName" : "eOhY4Wp6QNUtEjVTdmBff8UDY5p2",
      }

But the issue with this is that I can't have multiple users with the same username/ I don't think it's possible to have multiple nodes that have the same key.

Is this the best method to approach this situation? Or is there an alternative to have the same username (I don't want to pull down the whole users using snapshot since this would be super data intensive). If this is the best method I was figuring I would go in and manually change the duplicates that are already in the database.

Edited Additional Content:

Here is the only approach I know of to get usernames from first structure would be to get the whole snapshot and then filter for users with the username- this would download the entire snapshot which is super data intensive since I only need the users that have the username that I am searching for:

const snapshot = await firebase.child("Users").on("value")

I know there is the OrderBy method, but isn't that a top level approach/ wouldn't I need "testName" directly under users rather than 2 layers deeper.

    const snapshot = await firebase.child("Users").orderByChild("username")
   .equalTo('testName')

Since your user name is in a property that is nested under a known path, you can query it like this:

firebase.child("Users")
   .orderByChild("meta/username")
   .equalTo('testName')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM