Firebase获取所有用户名&用户ID以用户输入的字符开头 [英] Firebase get all usernames & user Id starting with user entered character

查看:88
本文介绍了Firebase获取所有用户名&用户ID以用户输入的字符开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅获取仅以用户输入的文本开头的用户名和用户ID.

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

下面是我的Firebase数据库:

Below is my firebase database:

如您所见,数据库包含一个包含用户名的用户ID列表.

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

例如:如果用户在搜索框中输入M,则查询应 返回Jois先生,它是相应的用户ID.

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

我正在尝试使用javascript做到这一点.下面是我的代码:

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?

推荐答案

Firebase数据库查询进行前缀匹配,而不是包含.但是,由于仅指定startAt(...),因此查询将匹配名称以前缀开头的所有用户,包括其后的所有名称.如果只需要以前缀字符串开头的结果,则还需要使用endAt(...):

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);
});

这篇关于Firebase获取所有用户名&用户ID以用户输入的字符开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆