Reputation: 39
I am trying to learn firebase a little by doing, so I might have modeled my DB wrongly.
Anyhow, I was wondering If there was a way to search all comments that have the value of a certain email. Let me show you the structure of my DB
I tried reading the docs, and tried a couple of things that did not work, for example:
const fetchComments = async () => {
const commentRef = await db.collection("comments")
return commentRef.where("email", '==', "[email protected]").get()
}
fetchComments().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
});})
But logging does not return anything, and if you log the querySnapshot I get of course an object with a bunch of stuff, but it seems witout data
So I was wondering, first, is there a way to get all comments that have a certain email? Or, if basically I structured all of my data in the wrong way and its impossible to get them.
Thanks
Upvotes: 0
Views: 61
Reputation:
The important thing to note is, firestore will always return the whole document from a query.
Firebase documentation as of today allows you to add following conditions in a where clause:
<
, <=
, ==
, >
, >=
, array-contains
, in
, or array-contains-any
.
The one condition which comes closest to your use case is
array-contains: If you have an array stored inside your document, e.g.:
liked_by: ["user1", "user2", "user3"]
you can run a query with where clause .where('liked_by', 'array-contains', 'user1')
and it will return you all the documents which have an array named liked_by
in them containing the string 'user1'. If you have stored objects in an array, like
comments: [
{
text: "comment",
user_id: "user1",
date: "dd/mm/yyyy"
}, ...
]
you will have to put the entire object in the where clause, eg:
.where('comments', 'array-contains', {text: "comment", "user_id: "user1", date: "dd/mm/yyyy"})
and that will return all documents containing an array named comments and having the exact object as in your where clause.
In your case, you have an array of comments in each document, so unless you happen to know the entire object, it won't be possible for you to query for such document.
If those document IDs (1,2,3...) are important to you, I would suggest you the following structure:
comments:{ // collection name
"random_document_id_created_by_firestore": {
// doc ids are assigned automatically by firestore when you use the add method.
// refer: https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document
"comment": "comment text",
"datePosted": "dd/mm/yyyy",
"email": "[email protected]",
"id": 9993,
"docId": 1 // add the key name (docId) as per your choice, e.g. postId
}, ...
}
Then, you can chain multiple where clauses in your query to filter your data as needed:
.where('docId', '==', 1).where('email', '==', '[email protected]').get()
Upvotes: 1