It is written in the documentation below that "If you need to query data across collections, use root-level collections." https://cloud.google.com/firestore/docs/data-model
If anyone knows an example of querying data across root-level collections in Firestore then please share the same.
I'm not sure of your specific scenario. Here's how to get comments (from 'commentsCollection' collection) related to an article.
Assume article documents are set up like this:
firestore: articlesCollection/1234
{
title: "How to FireStore",
}
And comments documents are set up like this:
firestore: commentsCollection/ABCD
{
comment: "Great article!",
articleRef: {
"1234": true
}
}
firestore: commentsCollection/EFGH
{
comment: "Another comment on a different article",
articleRef: {
"5678": true
}
}
Given an article document id...
let articleComments = db.collection("commentCollection")
.where('articleRef.' + articleId, '==', true)
.get()
.then(() => {
// ...
});
If the given article id were 1234, the comment ABCD would be the result. If the given article id were 5678, the comment EFGH would be the result.
Including the article doc query it would look something like this:
db.collection("articlesCollection")
.doc(articleId)
.get()
.then(article => {
firebase.firestore().collection("commentsCollection")
.where('articleRef.' + article.id, '==', true)
.get()
.then(results => {
results.forEach(function (comment) {
console.log(comment.id, " => ", comment.data());
});
});
});
Modified from firestore docs: https://cloud.google.com/firestore/docs/solutions/arrays
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With