0

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 =>

  1. johny => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
  2. johnathan => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
  3. tommy => {location:'', bio:'', createdAt, imageUrl, email:'', userId:'', etc}
  4. etc..
  • I don't understand your question. Is there something not working with what you've written so far? Or are you just asking for an opinion about what to do differently? Questions asking for opinion are off-topic for Stack Overflow - you should post to a discussion forum instead, such as Reddit. – Doug Stevenson Aug 23 '22 at 23:03
  • Yes, sorry. It's a question. The code is not working as I cant retrieve the doc ids based on the input text. – Calvin Heath Aug 23 '22 at 23:07
  • Please edit the question to show all the information someone can use to reproduce the issue (and remove any questions asking for opinion, as your last sentence asks now). We can't see the value of `search`, nor can we see the data in your documents. It might help to read about how to create a [complete minimal example](https://stackoverflow.com/help/minimal-reproducible-example) that someone can use to duplicate the behavior. – Doug Stevenson Aug 23 '22 at 23:13
  • You need to set an upper range on your query. Right now you are asking for **everything** greater than "john". – Doug Stevenson Aug 24 '22 at 00:06

0 Answers0