8

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?

user5863509
  • 255
  • 1
  • 4
  • 16

1 Answers1

4

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 6
    How? Please elaborate. – Olu Adeyemo Aug 22 '18 at 17:28
  • @franc There's no one solution that solves all needs. You would need to describe your collections and documents, and the results you intend to get from them. A solution is highly contextual to your needs. – Doug Stevenson Aug 22 '18 at 17:34
  • 1. Iterate all employees. Create a map of arrays and add every employee to the array associated with the department I'd (the key of the map entry). 2. Query the departments for all the Dept ids (the keys of the map) 3. Iterate the results and find the array of target objects for each dept id. Iterate the list and insert the dept name into it. – Richard Haven Mar 09 '23 at 21:48