TypeError: snapshot.forEach is not a function

点点圈 提交于 2021-01-05 11:34:42

问题


I am new to nodejs and Google Cloud FireStore.

So here is my code.

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);

The following error is shown when I run the application.

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' }

回答1:


You are passing in a firestore query for a specific document, in which case .get() would return the document, not a snapshot. You would get back a snapshot if you queried the collection, like with a .where(). Since you'll get back a doc instead of a snapshot, you would use it like this:

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);


来源:https://stackoverflow.com/questions/59384574/typeerror-snapshot-foreach-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!