Firebase get all usernames & user Id starting with

2019-08-27 22:04发布

问题:

I am trying to only fetch username and user IDs that only start with the User entered text.

Below is my firebase database:

As you can see the database contains a list of user Ids which contains the username.

For Example: If the user enters M in the search box, Query should return Mr Jois and it's the corresponding user ID.

I am trying to do this using javascript. Below is my code:

function* searchUsers(action) {
    const database = firebase.database();
    const ref = database.ref('users');
    try {
        console.log('about to fetch filters users');
        const query = ref.orderByChild('username').startAt(action.searchText);
        const snapshot = yield call([query, query.once], 'value');
        console.log('done fetching users');
        console.log(snapshot);
    }
    catch(error){
        console.log(error);
    }
}

But I am not getting the expected results. Can someone please tell me how to query the result to get the expected result?

回答1:

Firebase Database queries do a prefix match, not a contains. But since you only specify startAt(...) the query matches all users from the ones whose name starts with the prefix, including all names after it. If you only want results that start with the prefix string, you'll want to also use endAt(...):

const query = ref.orderByChild('username').startAt(action.searchText)endA‌t(action.searchText+‌​"\uf8ff");
const snapshot = yield call([query, query.once], 'value');
snapshot.forEach(function(child) { 
  console.log(child.key, child.val().username);
});


回答2:

Initially, I was thinking the equalTo() query along with Firebase .indexOn the username.

However, what we really need is a substring like ECMAScript 6's String.prototype.startsWith() method:

.startsWith(inputValue);

So, The only way I see to do it with realtime DB is to get/fetch/.once it then process client side where you have more robust string matching capability. I guess the next question is how to pull/fetch only the username property of each user key.



回答3:

To query based on the first character, you should get that character and pass it to the startAt() function:

const query = ref.orderByChild('username').startAt(action.searchText.charAt(0));