'Firebase query object key in array with Javascript
I have a db structure as:
user = {
name: 'xxx',
address: 'XXX YY ZZZ',
updates: [
{
created: '09/03/2022',
content: { message: 'Message #1132'},
....
}
]
}
I want to query any user that have updates.content.message contains the word 'Message' with firebase web version.
Thanks a lot!
Solution 1:[1]
There's no native like query on Google Cloud Firestore. But you can manage to create a workaround using nodejs/javascript. See code below:
var collection = "user";
// search input. you can change this to any word like in the comment you said that you want to find document that contains "test".
search = "Message";
// gets the length of the search input.
searchLength = search.length;
// logically change the last character of the search input to imitate the `like` query.
searchFront = search.slice(0, searchLength-1);
searchEnd = search.slice(searchLength-1, search.length);
// will result to "Messagf".
end = searchFront + String.fromCharCode(searchEnd.charCodeAt(0) + 1);
const query = db
.collection(collection)
.where('updates.content.message', '>=', search).where('updates.content.message', '<', end)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data());
});
});
The above code will search the updates.content.message that contains the word 'Message'. I leave some comments on the code for a better explanation. I'm not sure though if you're using Firestore v8 or v9 but the above code is written on v8.
Result:
drh13VT3T6n5bBHNARYD => {
address: 'XXX YY ZZZ',
name: 'xxx',
updates: { created: '09/03/2022', content: { message: 'Message #1132' } }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc Anthony B |
