User
User

Reputation: 89

How to query normalized firestore database

I have a Firestore Database that looks like this:

Root
    Accounts
            username: UID1
    Friends
            id: SOME_ID
            members: {UID1, UID2}

I display all the friends in a RecyclerView. But how can I use the username field in the Accounts collection to query the Friends List?

Upvotes: 1

Views: 361

Answers (2)

vantaku ramesh
vantaku ramesh

Reputation: 39

app.get("/player/:id", async (req, res) => {
  
  let { id: playerId } = req.params;
  if (!playerId) {
    res.status(400).send({
      success: false,
      message: "Kindly provide player ID",
    });
    return 0;
  }
  try {
    const snapshot = await admin
      .firestore()
      .collection("players")// players root user
      .doc(playerId)  //  sub folder   
      .get();
    let userData = snapshot.data();
    if (userData) {
      res.status(200).send({ ...userData });
      return 0;
    } else {
      res.status(400).send({
        success: false,
        message: "player does not exists in database",
      });
    }
  } catch (err) {
    res.status(400).send({ success: false, message: err.message });
  }
});

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599591

With your current data model you'll have to load each friend's user profile separately based on their UID to get their username.

Alternatively you can change your data model to also include the user name for each member in the Friends document already. While this data duplication may seem unnatural if you come from a background in relational databases, it is really common in NoSQL databases - and one of the reasons they scale so well when reading data.

To learn more about this, also check out:

Upvotes: 1

Related Questions