I have a collection in Firestore named "users". Each document has as an id a value with the name of the user. I want to create a search bar on my frontend and search by name in the collection of users and limit the result to at least 10 close matches. For example, if I type "Fr" in the input, I should get a list with usernames like Fred, Frederick, Francis, etc!
Despite my exhaustive investigation, I was unable to come up with a solution. Additionally, I did not want to use a third-party service like Algolia for Full Text Search because in my situation, I simply want to query the list of document IDs. The following code does not work as it fetches everything in the users collection.
const db = admin.firestore();
exports.queryUsers = (req, res) => {
let search = "john";
let users = [];
return db
.collection('users')
.where(admin.firestore.FieldPath.documentId(), '>=', search)
.limit(10)
.get()
.then((data) => {
data.forEach((doc) => {
users.push(doc);
});
return res.status(200).json(users);
});
};
Firestore schema:
users =>
- johny => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
- johnathan => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
- tommy => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
- etc..