Firestore 查询 - 加入两个集合 [英] Firestore Query - Joining two collections

查看:20
本文介绍了Firestore 查询 - 加入两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆