Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Query - Joining two collections

I am new to firestore. I want to get the name from a different collection by using join query by ID. How can I do that in firestore?

Here is some sample collection.

I have two collection.Employee and department.

Department collection:
 1001 --> DeptId : 1001
          DeptName : Account
 1002 -->  DeptId : 1002
           DeptName : HR

Employee collection

2001 --> empId : 2001
         DeptId :1001
         empName : Jon
2002 -->  empId : 2002
         DeptId : 1002
         empName : Steve

I want to query employee collection and wants to add dept document as part of the response. Here is sample response I am trying to get.

{
  "empid": 2001,
  "empname" : Jon
  "Dept" :{
    "Id" :1001,
    "DeptName" : HR
  } 
}

Here is my sample code to get employee data.

function getEmployee(req, res)
{
 var empId = req.query.empId;
var obj = admin.firestore().collection('employee').doc(empId);
  obj.get()
 .then(function(emp) {
   if (emp.exists) {       
       return res.status(200).send(JSON.stringify(emp.data()));
   } else {              
       return res.status(200).send('not found');
   }
})
.catch(function(error) {
   res.status(500).send('Error getting data.' })
});
}

How to add dept object to this employee?

like image 946
user5863509 Avatar asked Jun 29 '18 23:06

user5863509


People also ask

How do you query collections in firestore under a certain path?

There is no way to get documents from different collections or sub-collections in a single query. Firestore doesn't support queries across different collections in one go unless we are using a collection group query.

How do I query multiple values in firestore?

With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.

Can you use SQL in firestore?

FireSQL is a library built on top of the official Firebase SDK that allows you to query Cloud Firestore using SQL syntax. It's smart enough to issue the minimum amount of queries necessary to the Firestore servers in order to get the data that you request.

What is QuerySnapshot in Firebase?

A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. The number of documents can be determined via the empty and size properties.


1 Answers

Firestore has no join queries. If you want to combine the data from two documents, you will have to query them individually, then compose your response based on the data from both.

like image 50
Doug Stevenson Avatar answered Oct 18 '22 19:10

Doug Stevenson