我在node.js上使用firebase。
我给定的结构应该如下所示:
{
...
batch-1:
id-1(suppose):
name:...
phone:...
id-2:
...
id-3:
...
batch-2:
...
batch-3:
...
...
batch-n:
...
}在这样的体系结构中,如何通过id-1对象的标识符来获取id-1对象呢?数据库必须绕过所有的批次吗?有没有更好的解决办法?主要任务:创建一个具有短和唯一标识符的多个对象的批处理,并通过此标识符最优地接收数据。
发布于 2019-12-11 16:22:24
若要搜索作为未知ID列表的子ID的特定ID,需要使用orderByChild()。在您的用例中,您要在批处理ID列表中查找特定的ID。如果在此列表中使用orderByChild(),则会得到每个批处理ID的结果,即使它没有所需的ID。这是因为即使是null (不存在的)值也包含在结果中(并在开始时进行排序)。要获取所需ID的数据,您将获得查询的最后结果的数据,如果存在的话,数据将是排序到列表的末尾。注意,如果不存在所需的ID,则最后一个结果(如果有任何结果)将有一个null值。若要只返回查询的最后结果,请使用limitToLast(1)。
将所有这些组合在一起,将给出以下代码:
let idToFind = "unique-id-1";
let batchesRef = firebase.database().ref(); // parent key of "batch-1", "batch-2", etc.
// assumed to be the database root here
batchesRef.orderByChild(idToFind).limitToLast(1).once('value')
.then((querySnapshot) => {
if (!querySnapshot.numChildren()) { // handle rare no-results case
throw new Error('expected at least one result');
}
let dataSnapshot;
querySnapshot.forEach((snap) => dataSnapshot = snap); // get the snapshot we want out of the query's results list
if (!dataSnapshot.exists()) { // value may be null, meaning idToFind doesn't exist
throw new Error(`Entry ${idToFind} not found.`);
}
// do what you want with dataSnapshot
console.log(`Entry ${idToFind}'s data is:`, dataSnapshot.val());
})
.catch((error) => {
console.log("Unexpected error:", error);
})对于小数据集,上面的代码工作得很好。但是,如果批处理列表开始变得相当大,您可能希望构建一个索引,将特定ID映射到包含它的批处理ID。
发布于 2021-02-27 00:05:29
下面是我的方法,它允许您按id进行搜索或按键值(如email uniqueemail )进行搜索。
// gets primary key
const getSnapshotValKey = snapshot => (Object.keys(snapshot).length > 0 ? Object.keys(snapshot)[0] : null)
const getUser = async ({ id, key, value }) => {
let user = null
const ref = id ? '/users/' + id : 'users'
const userRef = admin.database().ref(ref)
const valueRef = id ? userRef : await userRef.orderByChild(key).equalTo(value)
const snapshot = await valueRef.once('value')
const val = snapshot.val()
if (val) {
const key = id || getSnapshotValKey(val)
user = {
id: key,
...(id ? val : val[key]),
}
}
return user
}https://stackoverflow.com/questions/59283028
复制相似问题