我是Nodejs和Google Cloud FireStore的新手。
这是我的代码。
createNewPage = function (title, header, content, db ) {
let pageRef = db.collection("pages").doc(title.trim());
let setPage = pageRef.set({
title: title,
header: header,
content: content
});
return pageRef;
}
const printPage = function(Page)
{
Page.get().then(snapshot => {
if (snapshot.empty){
console.log("No matching documents");
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>',doc.data())
})
})
.catch(err => {
console.log(err);
});
}
let newPage = createNewPage("Contact Us", "Please contact us", "<p> fill this </p>", db);
printPage(newPage);
运行应用程序时显示以下错误。
TypeError: snapshot.forEach is not a function
at Page.get.then.snapshot (C:\Code\Node\ps1331\app.js:59:18)
at process._tickCallback (internal/process/next_tick.js:68:7)
homepage => { content: '<h2> Hello World </h2>',
header: 'Welcome to the home page',
title: 'Home Page' }
答案 0 :(得分:2)
您正在传递Firestore查询特定文档,在这种情况下,.get()
将返回该文档,而不是快照。如果查询集合,您将获得快照,例如使用.where()
。由于您将取回文档而不是快照,因此可以这样使用它:
createNewPage = function(title, header, content, db) {
let pageRef = db.collection("pages").doc(title.trim());
let setPage = pageRef.set({
title: title,
header: header,
content: content
});
return pageRef;
}
const printPage = function(Page) {
Page.get().then(doc => {
if (doc && doc.exists) {
console.log(doc.id, '=>', doc.data());
}
})
.catch(err => {
console.log(err);
});
}
let newPage = createNewPage("Contact Us", "Please contact us", "<p> fill this </p>", db);
printPage(newPage);