首页 > 解决方案 > Firebase 获取具有特定输入字符串的所有文档

问题描述

let info = "every doc that starts with input preferable where i can place a limit on"
firebase.firestore().collection("usernames").doc(info);

我想创建一个搜索栏,根据我输入的值获取所有用户。而且我不确定如何做到这一点。基本上我想获取集合用户名中包含一些输入字符串的所有文档

标签: javascriptdatabasefirebasegoogle-cloud-firestore

解决方案


首先,您对上面的代码所做的就是创建一个 id 为字符串 'info' 的文档。只能存在一个唯一 ID,这将使查询变得不必要。为了进行字符串搜索,最好将字符串拆分为数组。我假设你想要做的是这样的:

let info = "some string to go in document"
info = info.split(" ");

// Add a new document with a generated id.
firebase.firestore().collection("usernames").add({
    info: info
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

然后可以查询集合中的所有文档,查看 info 数组是否包含某个字符串单词:

let check = "string"

firebase.firestore().collection("usernames").where('info', 'array-contains', check).get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
    });
});

希望这有帮助,这是一个难题


推荐阅读