TypeError: snapshot.forEach is not a function

Posted on

TypeError: snapshot.forEach is not a function

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:CodeNodeps1331app.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' }

Solution :

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

Leave a Reply

Your email address will not be published. Required fields are marked *