Firestore查询-连接两个集合 [英] Firestore Query - Joining two collections
问题描述
我是Firestore的新手.我想通过按ID使用联接查询来从其他集合中获取名称.我该如何在Firestore中做到这一点?
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?
这是一些样本集合.
我有两个集合,雇员和部门.
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?
推荐答案
Firestore没有联接查询.如果要合并来自两个文档的数据,则必须分别查询它们,然后根据来自两个文档的数据来组成响应.
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.
这篇关于Firestore查询-连接两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!