Firestore查询-连接两个集合

时间:2018-06-29 23:59:15

标签: javascript node.js google-cloud-firestore

我是Firestore的新手。我想通过按ID使用联接查询来从其他集合中获取名称。我该如何在Firestore中做到这一点?

这是一些样本集合。

我有两个集合,雇员和部门。

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

我想查询员工集合,并想添加部门文档作为响应的一部分。 这是我尝试获取的示例响应。

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

这是我获取员工数据的示例代码。

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.' })
});
}

如何向该员工添加部门对象?

1 个答案:

答案 0 :(得分:2)

Firestore没有联接查询。如果要合并两个文档中的数据,则必须分别查询它们,然后根据两个文档中的数据来组合响应。

相关问题