how can i join search results on firebase?

Alright, first let me confirm I understand the SQL.

You’re wanting to return two variables (title, email) from the User table

SELECT post.title as "Post Title", user.email as "Author Email"
FROM User 

Then you want to join the Post table where the ‘User.id’ is equal to the ‘Post.userID’ so essentially finding the users’ posts.

JOIN Post ON User.id = Post.userID
WHERE Post.title LIKE '%retriever%';

If my assessment is accurate, and without knowing your data model, I can give a rough guess on what that would look like.

//Reference to Firestore
const db = firebase.firestore() 

//Reference to the Post "table" Collection
const ref = db.collection('Post')

//This is assuming I know the USER ID that I need - if I don't have it, we can retrieve it by their email 'admin.auth().getUserByEmail(email)' or somewhere else.
//This example should still work with whatever the 'id' key is representing in the Post model
    const postsByUserID = await ref.where('id', '==', userID).get();

if (postsByUserID.empty) {
  console.log('No matching documents.');
  return;
}  

//This will loop through every Post that we got that matched the user's ID
postsByUserID.forEach(doc => {
  console.log(doc.id, '=>', doc.data());
});

Keep in mind this is assuming that ‘id’ from your Post model is equal to a user’s UID.

If we assume we do not know the user’s ID, and want to get every user, and then the posts that have the ‘id’ equal to that user’s id:

//Reference to the Post "table" Collection
const ref = db.collection('Users')

const allUsers = await ref.get();

allUsers.forEach(doc => {
  console.log(doc.id, '=>', doc.data());
  const userID = doc.data().id;

  const postsByUserID = await ref.where('id', '==', userID).get();

  if (postsByUserID.empty) {
    console.log('No matching documents.');
    return;
  }  

  //This will loop through every Post that we got that matched the user's ID
  postsByUserID.forEach(doc => {
    console.log(doc.id, '=>', doc.data());
  });

});

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top