Jon*_*son 11 javascript node.js firebase google-cloud-platform google-cloud-firestore
我在查询 Firestore 数据库中子集合内的所有文档时遇到困难。(我正在使用 Node.js)
我的目标是从名为的子集合中的每个文档获取所有数据favorites
我的数据库结构如下所示。

我查看了https://firebase.google.com/docs/firestore/query-data/get-data上的文档,但没有任何结果如何解决问题。
我的查询现在看起来像这样:
exports.getAllFavoritePodcasts = (req, res) => {
db.collection('users')
.doc(req.user.userId)
.collection('favorites')
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
}
Run Code Online (Sandbox Code Playgroud)
但我得到TypeError: db.collection(...).doc(...).collection(...).then is not a function
小智 15
如果子集合(subcoll)包含3个文档(doc1,doc2,doc3),如下所示:
coll > doc > subcoll > doc1 > field1:“值1”,field2:“值2”
doc2 > 字段1:“值1”,字段2:“值2”
doc3 > 字段 1:“v1”,字段 2:“v2”
您可以使用以下代码获取子集合(subcoll)的所有3个文档(doc1,doc2,doc3) :
coll > doc > subcoll > doc1 > field1: "value1", field2: "value2"
doc2 > field1: "value1", field2: "value2"
doc3 > field1: "v1", field2: "v2"
没有forEach() 方法来获取下面子集合(subcoll)的所有 3 个文档(doc1、doc2、doc3):
import { getDocs, collection } from "firebase/firestore";
const docsSnap = await getDocs(collection(db,"coll/doc/subcoll"));
docsSnap.forEach((doc) => {
console.log(doc.data()); // "doc1", "doc2" and "doc3"
});
Run Code Online (Sandbox Code Playgroud)
此外,您还可以使用下面的while获取子集合(subcoll)的 2 个文档(doc1,doc2):
import { getDocs, collection } from "firebase/firestore";
const docsSnap = await getDocs(collection(db, "coll/doc/subcoll"));
console.log(docsSnap.docs[0].data()); // "doc1"
console.log(docsSnap.docs[1].data()); // "doc2"
console.log(docsSnap.docs[2].data()); // "doc3"
Run Code Online (Sandbox Code Playgroud)
没有forEach() 方法来获取子集合(subcoll) 的 2 个文档(doc1, doc2),如下所示:
import { query, collection, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "coll/doc/subcoll"),
where("field1", "==", "value1"));
const docsSnap = await getDocs(q);
docsSnap.forEach((doc) => {
console.log(doc.data()); // "doc1" and "doc2"
});
Run Code Online (Sandbox Code Playgroud)
另外,您还可以使用以下代码获取子集合(subcoll)的一个特定文档(doc3) :
import { query, collection, where, getDocs } from "firebase/firestore";
const q = query(collection(db, "coll/doc/subcoll"),
where("field1", "==", "value1"));
const docsSnap = await getDocs(q);
console.log(docsSnap.docs[0].data()); // "doc1"
console.log(docsSnap.docs[1].data()); // "doc2"
Run Code Online (Sandbox Code Playgroud)