【发布时间】:2018-10-08 19:37:16
【问题描述】:
我正在使用带有 Firebase 数据库的 node-express JS 编写 Rest API。在 Firebase 中,我有两个集合,例如:
Bin (binName, binLocaton, hardwareId)
BinsInformation (date, payloadFields { hardwareId, levle })
如何根据字段hardwareId 加入这两个集合?
I would like to join to collections like two tables in MySQL.
Ex. "SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id "
Like the above MySQL query i would like join my two collections "Bin" and "BinInformation".
如果我加入具有特定 id 的单个文档,它会给出正确的输出。但是当我试图加入两个集合中的所有文档时 使用单独的查询给出“异步错误”。
这是我的收藏:
垃圾箱:
[
{
AreaID: "ZYwQHIrZPEDd359e6WRf"
Capacity: "123"
Latitude: "17.658745"
LocationName: "testing"
Longitude: "78.9874545"
hardwareid: "4321"
},
{
AreaID: "ZYwQHIrZPEDd359e6WRf"
Capacity: "123"
Latitude: "17.658745"
LocationName: "testing"
Longitude: "78.9874545"
hardwareid: "5432"
}
]
Bin 信息:
[
{
date: September 24, 2018 at 12:00:00 AM UTC+5:30,
payload_fields: {
hardwareid: "4321"
level : 60
}
},
{
date: September 24, 2018 at 12:00:00 AM UTC+5:30,
payload_fields: {
hardwareid: "5432"
level : 23
}
}
]
这里我需要获取所有带有相应 BinInformation 的 Bins。我的代码是这样的
app.get('/twoColectionJoin', asyncHandler( async (req, res, next) => {
console.log('await');
try {
let allDocs = [];
const snapshot = await db.collection('Bins').get();
let i = 0;
snapshot.forEach( async (doc) => {
let dummyDoc = doc.data();
const details = await getBinDet(dummyDoc.hardwareid);
dummyDoc.id = doc.id;
dummyDoc.det = details;
allDocs.push(dummyDoc);
i++;
console.log(allDocs);
});
res.status(200).send(allDocs);
}
catch(e){
next(e);
}
}) );
async function getBinDet(hardwareid){
let dummyDoc = {};
return new Promise(function(resolve, reject){
try{
setTimeout(function(){
db.collection('BinsInformation')
.where('payload_fields.hardwareid', '==', hardwareid)
.limit(1).get()
.then(snap => {
snap.forEach(element => {
//return element.data();
dummyDoc = element.data();
});
resolve(dummyDoc);
})
.catch(err2 => {
reject(err2);
});
}, 300);
}catch(err){
console.log(err);
}
});
}
预期输出:
[
{
AreaID: "ZYwQHIrZPEDd359e6WRf"
Capacity: "123"
Latitude: "17.658745"
LocationName: "testing"
Longitude: "78.9874545"
hardwareid: "4321",
det: {
date: September 24, 2018 at 12:00:00 AM UTC+5:30,
payload_fields : {
hardwareid: "4321"
level : 60
}
}
},
{
AreaID: "ZYwQHIrZPEDd359e6WRf"
Capacity: "123"
Latitude: "17.658745"
LocationName: "testing"
Longitude: "78.9874545"
hardwareid: "5432",
det: {
date: September 24, 2018 at 12:00:00 AM UTC+5:30,
payload_fields: {
hardwareid: "5432"
level : 23
}
}
}
]
但结果输出是:[]
【问题讨论】: