Firebase JS - 像 mySQL 一样查询

问题描述 投票:0回答:1

我一遍又一遍地搜索,但仍然找不到以下问题的答案或提示:

使用 SQL 我可以查询如下: 从表中选择 *,其中 X = Y 且 A != B(在示例中)

Firebase 不是 SQL - 到目前为止我明白了!但是如果我有这样的结构怎么办:

Users
   Id1
      Username: User 1
      Country: US
      Other: One
   Id2
      Username: User 2
      Country: CA
      Other: Two

   Id3
      Username: User 3
      Country: US
      Other: Three

如何才能只获得美国国家/地区的用户? 其次,我怎样才能只获得国家=美国和其他=三的用户?

我实际上拥有的是以下代码:

const dbRef = ref(getDatabase());
get(child(dbRef, `users/`)).then((snapshot) => {
let userArray = [];
snapshot.forEach(function(childSnapshot){
userArray.push(childSnapshot.val());

那么有人可以通过代码示例给我一些提示吗?

javascript firebase
1个回答
0
投票

您可以使用

orderByChild()
equalTo()
方法来完成此操作。

const dbRef = ref(getDatabase());
// Get users with Country = US
const usersRef = child(dbRef, 'users');
const usersWithUSCountryRef = query(usersRef, orderByChild('Country'), equalTo('US'));

get(usersWithUSCountryRef).then((snapshot) => {
    let usersWithUSCountry = [];
    snapshot.forEach((childSnapshot) => {
        usersWithUSCountry.push(childSnapshot.val());
    });
    console.log('Users with Country = US:', usersWithUSCountry);
}).catch((error) => {
    console.error('Error getting users with Country = US:', error);
});

// Get users with Country = US and Other = Three
const usersWithUSThreeRef = query(usersRef, orderByChild('Country'), equalTo('US'));
const usersWithUSThree = [];

get(usersWithUSThreeRef).then((snapshot) => {
    snapshot.forEach((childSnapshot) => {
        const userData = childSnapshot.val();
        if (userData.Other === 'Three') {
            usersWithUSThree.push(userData);
        }
    });
    console.log('Users with Country = US and Other = Three:', usersWithUSThree);
}).catch((error) => {
    console.error('Error getting users with Country = US and Other = Three:', error);
});
© www.soinside.com 2019 - 2024. All rights reserved.