如何从firebase函数访问firestore

如何从firebase函数访问firestore,firebase,google-cloud-firestore,google-cloud-functions,Firebase,Google Cloud Firestore,Google Cloud Functions,我已经为一个无服务器web应用程序启动了一个Firebase项目。从客户端,我可以访问Firestore数据库。在无服务器端,我编写了一个在http请求时调用的函数。函数试图通过Firestore对象访问数据库,但失败了,因为Firestore对象没有我认为应该具有的collection()函数。在输出中,我显示Firestore对象的内容 const functions = require('firebase-functions'); exports.noteList = functions

我已经为一个无服务器web应用程序启动了一个Firebase项目。从客户端,我可以访问Firestore数据库。在无服务器端,我编写了一个在http请求时调用的函数。函数试图通过Firestore对象访问数据库,但失败了,因为Firestore对象没有我认为应该具有的collection()函数。在输出中,我显示Firestore对象的内容

const functions = require('firebase-functions');

exports.noteList = functions.https.onRequest((req, res) => {
  db = functions.firestore;
  console.dir(db);
  db.collection("notes").listDocuments().then(documentRefs => {
   return db.getAll(documentRefs);
  }).then(documentSnapshots => {
   res.json(documentSnapshots);
  });
});
输出:

{ provider: 'google.firestore',
  service: 'firestore.googleapis.com',
  defaultDatabase: '(default)',
  document: [Function: document],
  namespace: [Function: namespace],
  database: [Function: database],
  _databaseWithOpts: [Function: _databaseWithOpts],
  _namespaceWithOpts: [Function: _namespaceWithOpts],
  _documentWithOpts: [Function: _documentWithOpts],
  DatabaseBuilder: [Function: DatabaseBuilder],
  NamespaceBuilder: [Function: NamespaceBuilder],
  snapshotConstructor: [Function: snapshotConstructor],
  beforeSnapshotConstructor: [Function: beforeSnapshotConstructor],
  DocumentBuilder: [Function: DocumentBuilder] }
Function crashed
TypeError: db.collection is not a function
为了进行比较,这是我从客户端访问数据库的方式,这是可行的:

function main() {
  var db = firebase.firestore();
  db.collection("global").doc("public").get().then(
    function(r) {
      var number_span = document.getElementById("number_span");
      data = r.data();
      number_span.textContent = "" + data.counter;
    });
}

当然,firebase对象是通过不同的方式获得的。可能缺少某些配置?

您需要使用Firestore SDK(通常通过)来访问Firestore。云函数SDK(firebase函数)不会为您执行此操作。它所做的只是帮助您指定要部署的功能。函数体应使用Firestore SDK

// require and initialize the admin SDK
const admin = require('firebase-admin');
admin.initializeApp();

// now use the SDK in the body of the function
admin.firestore().collection(...).doc(...)
AdminSDK只是包装了API,所以使用它的引用来导航API