Reputation: 121
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.
Upvotes: 8
Views: 9588
Reputation: 91
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
Upvotes: 1