本文介绍了TypeError:snapshot.forEach不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Nodejs和Google Cloud FireStore的新手.

I am new to nodejs and 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);

运行应用程序时显示以下错误.

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

推荐答案

您正在传递Firestore查询特定文档,在这种情况下,是 .get() 会返回文档,而不是快照.如果查询集合,您将获得快照,例如 .where() .由于您将取回文档而不是快照,因此可以这样使用它:

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

这篇关于TypeError:snapshot.forEach不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 17:31