[英]How to get data with specific field Firebase?
I have structure like this : 我有这样的结构:
{
2018-02-27: {
-L6MTxsb_aJoKhMNA6X0 : {
comment: ...
created: ...
price : ...
}
-L6MTxsb_aJoKhCNA6X0 : {
comment: ...
created: ...
price : ...
employeeId: ...
}
}
2018-02-27: {
-L6MTxsb_aJoKhMNA6X0 : {
comment: ...
created: ...
price : ...
}
-L6MTxsb_aJoKhCNA6X0 : {
comment: ...
created: ...
price : ...
employeeId: ...
}
}
How to get only that objects which have employeeId
key 如何仅获取具有
employeeId
键的对象
I need to pass parametr to function and get values which equals to this parametr I tried this: 我需要将参数传递给函数,并获取等于我尝试过的该参数的值:
export const loadForEmployee = async employeeId => {
let result = (await database('/balance/outcomes').orderByChild('employeeId').equalTo(employeeId ).once('value')).val() || {}
return result
}
But it returns {}
但它返回
{}
You're trying to search too deep into your database, and you have a typo in your orderByChild
method. 您试图在数据库中搜索过深,并且
orderByChild
方法中有错字。
Because your structure is broken down by date and reference key - you need to search through the timestamps then the children. 由于您的结构按日期和参考键进行了细分-您需要先搜索时间戳,然后再搜索子级。
{
2018-02-27: {
-L6MTxsb_aJoKhMNA6X0 : {
comment: ...
created: ...
price : ...
},
-L6MTxsb_aJoKhCNA6X0 : {
comment: ...
created: ...
price : ...
employeeId: ...
},
},
2018-02-27: {
-L6MTxsb_aJoKhMNA6X0 : {
comment: ...
created: ...
price : ...
},
-L6MTxsb_aJoKhCNA6X0 : {
comment: ...
created: ...
price : ...
employeeId: ...
},
},
};
You can pass the timestamp to the function as below; 您可以将时间戳传递给以下函数;
export const loadForEmployee = async (employeeId, timestamp) => {
const snapshots = await database('/balance/outcomes/' + timestamp)
.orderByChild('employeeId')
.equalTo(employeeId)
.once('value');
return snapshots.val() || {};
}
The other option is to iterate through all the results, but this will be fairly slow and intensive depending on how big your database is; 另一种选择是遍历所有结果,但是这将是相当缓慢和密集的,具体取决于数据库的大小。
export const loadForEmployee = async employeeId => {
const snapshots = await database('/balance/outcomes')
.once('value');
const results = {};
snapshots.forEach(snapshot => {
const timestamp = snapshot.key;
const outcomes = snapshot.val();
Object.keys(outcomes).forEach(key => {
const outcome = outcomes[key];
if (outcome.employeeId === employeeId) {
if (!results[timestamp]) {
results[timestamp] = {};
}
results[timestamp][key] = outcome;
}
});
});
return results;
}
I haven't tested this code, so it might not work verbatim but the general idea should be correct. 我尚未测试此代码,因此它可能无法逐字记录,但总体思路应该是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.