Firebase get all documents with specific input string [duplicate] - javascript

This question already has answers here:
Wildcard Firebase Query [duplicate]
(1 answer)
Google Firestore: Query on substring of a property value (text search)
(25 answers)
Closed 1 year ago.
let info = "every doc that starts with input preferable where i can place a limit on"
firebase.firestore().collection("usernames").doc(info);
I want to make a search bar where I get all users depending on the value I type in.
And I'm not sure how to do that exectly. basicaly I want to get all docs in the collection usernames that contain some input string

To start with, what you have done with the code above is create a document with an id of the string 'info'. Only one unique id could exist which would make querying unnecessary. In order to do a string search it would also be best to split the string into an array. II assume what you want to do is something like:
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);
});
Then you can query all documents in the collection to see if the info array contains a certain string word:
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());
});
});
Hope this is helpful, its a difficult problem

Related

how do I use a variable in find() method when looking for similar matches? [duplicate]

This question already has answers here:
How I can use "LIKE" operator on mongoose?
(7 answers)
Closed 1 year ago.
I am making a dictionary web app and now I am trying to make a search engine. I want to partly enter a word and get all of the similar matches. For example, I enter "ava", and get "lava" and "available" back. Mongoose has a method to do that but I need to enclose my query into slashes (like this /query/). I can do that with a string but I don't know how to put a variable in there in order to make a user search.
// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();
Here's my code:
app.post("/search", function(req, res){
let search = req.body.wordSearch;
console.log(req.body.wordSearch);
Dicword.find({word: /search/i}, function(err, searchRes) {
search = searchRes;
res.render("search", {search: search});
} );
})
I use let search to store the query and a result of a search but when I put it in find method with slashes /search/, it gets recognized as a string and not a variable. How can I use a variable there?
Instead of
{ word: /search/i }
Write like this
{ word: `/${search}/i` }

Array from GroupsApp and then indexOf fails [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Why doesn't indexOf find an array within the searched array? (Need explanation not solution) [duplicate]
(3 answers)
Closed 1 year ago.
I am trying to get a list of people in a Google Group with Google Apps Script. I made a code (below) but the result is unexpected. I think is realted with the format of the item but not sure. In my code i tested many logs to check that.
Why "indexOf" can not detect properly the email? Becuase -1.00 as answer is wrong.
Info:
getUsers() User[] Retrieves the direct members of the group that have a known corresponding Google account.
I think is weird indexOf answering -1.00 when i ask with "" and when i ask with the position of array answer properly.
I need to check in an script if someone is inside of this groups (inside loop for).
function CheckingSomeFromGroup() {
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
Logger.log(members); //it shows an array in the log
Logger.log(members[0]); //it shows the first element form that array which is "Jorge#company.com"
Logger.log(members.indexOf("Jorge#company.com") //i was expecting a number different than -1.00 because jorge exists but in the log appear -1.00 which is wrong
Logger.log(members.indexOf(members[0]); //it shows 0 correctly becuase Jorge is in the first place of the array
Logger.log(members.length);//it shows number 3 which is ok since i have 3 people in the group
}
members is an array of User object, not string. So you cannot just find it by email/string. You see email in the logger because it might have a toString method to output that.
You can loop on members and call User.getEmail() to get the email and work accordingly.
function CheckingSomeFromGroup() {
var emails = ['abc#example.com'];//get 1-D array of string emails from your column accordingly
var members = GroupsApp.getGroupByEmail("members#company").getUsers();
for (var i = 0; i < members.length; i++) {
var memberEmail = members[i].getEmail();
if (emails.indexOf(memberEmail) !== -1) {
//exists
}
}
}

Array-contains query not working react native [duplicate]

This question already has an answer here:
Firestore array-contains-any is not working properly
(1 answer)
Closed 3 years ago.
Hello i'm implementing the array-contain query but everytime i'm trying i'm Getting blank snapshot. My code is:
getStation = () => {
const query = firebase
.firestore()
.collection('routes')
.where('station', 'array-contains', 'station_name ');
query.get().then(snapshot => {
console.log("snapshot", snapshot);
snapshot.docs.forEach(doc => {
alert("eri")
console.log("eryh", doc.data);
})
})
.catch(err => {
console.log('Error getting documents', err);
});
}
I even tried to pass the static values but not able to get the desire value.
In your code there is a problem with typo mistake station must be stations
.where('station', 'array-contains', 'station_name ');
must be
.where('stations', 'array-contains', 'station_name ');
I hope it will fix your problem.
Update Answer
There is also typo mistake in station_name you just added the space after station_name
.where('station', 'array-contains', 'station_name ');
must be
.where('stations', 'array-contains', 'station_name');
You are trying to use array-contains to check for a field inside a map. This is not supported.
The array-contains can only search for a field inside the array and not a field inside a map which is inside that array.
A workaround I have tested is that you add an extra field inside the array that will be a boolean or a string and you can query based on it.
Using a boolean field in the array:
.where('stations', 'array-contains', true);
Using a String field in the array:
.where('stations', 'array-contains', 'station_name exists');
The array-contains operation checks if the precise object/value you specify exists in the array. It can't check on subsets of the array elements, only on complete values. So in your current structure, you'd have to pass all properties into the array-contains call:
.where('station', 'array-contains',
{ station_address_name: '...', station_lat_long: ..., status_name: '...' });
This typically is not feasible, in which case you'll want to store the elements that you want to filter on in a (additional) separate field in your documents. In this example, since you want to filter on station names, you'd add a field station_names where you store just the station names. Then you can query with:
.where('station_names', 'array-contains', 'name to search for')
Also see:
Firestore to query by an array's field value
Firestore array-contains-any is not working properly
How to make query spot only the some value in a Map inside an Array in flutter (dart)?

Firestore query 'array_contains' pass in array [duplicate]

This question already has answers here:
Firestore search array contains for multiple values
(6 answers)
Closed 3 years ago.
I am looking at Firebase, cloud firestore and I am not understanding how I would perform a query and pass in an array.
const friendIds = [1, 2, 3];
Firestone.collection('conversations')
.where('members', 'array-contains', friendIds)
.get()
.then(querySnapshot => console.log(querySnapshot))
.catch(error => console.log(error));
anyone know how to achieve this?
This is currently not possible with a single query. array-contains can only find a single item in the named array.
Your alternative is to perform three queries, one for each item in the friendsId array, then merge the results in your code.
Not sure if this is possible, but here's an example from the Firebase Node.js Snippets that can give you an idea:
let citiesRef = db.collection('cities');
// [START array_contains_filter]
let westCoastCities = citiesRef.where('regions', 'array-contains',
'west_coast');
// [END array_contains_filter]
westCoastCities.get()
.then(res => {
console.log('West Coast get: ', res);
});
Reference Documentation
According to the official documentation regarding query operators:
You can use the array-contains operator to filter based on array values.
As I can see in your code, your friendIds argument that is passed as the third parameter to the where() function is of type array. What you are actually doing, you are searching in the members property which is of type array for an array, which is actually not possible since I assume the members array in your database contains numbers.
An query like this:
Firestone.collection('conversations')
.where('members', 'array-contains', 3)
.get()
.then(querySnapshot => console.log(querySnapshot))
.catch(error => console.log(error));
Will work perfectly fine because we are searching within the members array for a number.
If you need to query for all those numbers, you should perform three separate queries and combine the result client side.

Firestore where query with parameter not working

I have a query that is not working as I expect it to. I have a collection called 'games' that has a number of documents in it.
Each document has an array called 'hiScores' that consists of the results from that round. I would like to query all games for a specific player for example:
.where('hiScores.playerName', '==', 'David Lamm')
This is not returning anything. I have no problems when querying a top level variable in the document. What have I done wrong?
Database:
db.collection('games')
.where('hiScores.playerName', '==', 'David Lamm')
.get()
.then(function(querySnapshot) {
console.log('Davids games:')
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
}
);
The problem is that the hiScores field is an array, not an object. You can tell it's an array because the first immediate element of the array in the screenshot has index 0. You're trying to query hiScores as if it's a single object with a single property called playerName.
Firestore doesn't support querying for object properties within within array fields. If you have an array field, you can only query to find documents where an entire item is present in the array (an arrayContains query).
As pointed out by Doug this is currently not possible in firestore.
You can create a top level array of strings in each game named playerNames[]. Then use the where condition on playerNames with array_contains.

Categories

Resources