I am trying to do a parameter search of an input and when I do my users search my query is bringing me all the data below the letter I type, can someone explain me what I am doing wrong ?
Search Query
const fetchUsers = (search) => {
firebase.firestore()
.collection('users')
.orderBy('username')
.startAt(search)
.get()
.then((snapshot) => {
let users = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
});
setUsers(users);
})
}
Result
What you're seeing is the expecting behavior. The startAt
(and it's siblings startAfter
, endAt
, and endBefore
) operation allows you to get a slice of the data. So your current query tells the database to order the documents on their username
field, and then start returning documents starting at search
in the results.
What you want to do is find documents where username
starts with the value you specify, which is a different operation. If you want to use the slice operators, you can do this by adding an endAt
:
firebase.firestore()
.collection('users')
.orderBy('username')
.startAt(search)
.endAt(search+"\uf8ff")
The \uf8ff
is just the last known Unicode character, so that gives you a slice of the data that starts with the search
term.