我正在使用NextJS和Typescript进行Firebase项目。我试图从Firestore数据库获取数据,我得到这个错误Type 'Promise<QuerySnapshot<DocumentData>>' must have a '[Symbol.iterator]()' method that returns an iterator.
这是我用来从db
获取数据的代码const postsRef = collection(db, "discussions");
query(postsRef, orderBy("createdAt"), limit(20));
const [posts] = getDocs(postsRef)
您的getDocs
不返回数组,这就是为什么您得到此错误。QuerySnapshot
是一个自定义的Firebase类型,它有forEach
(类似于一个数组),但是不是一个数组。所以你需要使用forEach
:
const postsRef = collection(db, "discussions");
query(postsRef, orderBy("createdAt"), limit(20));
// I'm guessing you need await here too?
const postDocs = await getDocs(postsRef)
let posts = []
postDocs.forEach((postDoc) => {
posts = [...posts, {
...postDoc.data(),
id: postDoc.id,
}]
})