如何从firebase函数访问firestore

Ema*_*ini 5 firebase google-cloud-functions google-cloud-firestore

我已经为无服务器 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

输出:

{ 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
Run Code Online (Sandbox Code Playgroud)

为了进行比较,这是我从客户端访问数据库的方式,这是有效的:

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;
    });
}
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*son 10

您需要使用 Firestore SDK(通常通过Firebase Admin SDK)来访问 Firestore。Cloud Functions SDK (firebase-functions) 不会为您执行此操作。它所做的只是帮助您指定要部署的功能。函数主体应使用 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(...)
Run Code Online (Sandbox Code Playgroud)

Admin SDK 仅包装Cloud Firestore Node SDK,因此请使用其参考来导航 API。