I have started a Firebase project for a serverless web application. From the client-side I can access the Firestore database. From the serverless-side I have written a function to be called on http request. The function is trying to access the database by means of a Firestore object but it is failing because the Firestore object has no collection() function as I think it should have. In the output I show the content of the Firestore object.
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);
});
});
output:
{ 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
For comparison this is how I access the database from the client-side, this is working:
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;
});
}
Of course the firebase object is obtained in different ways. Maybe some configuration is missing?
You need to use a Firestore SDK (typically via the Firebase Admin SDK) to access Firestore. The Cloud Functions SDK (firebase-functions) does not do this for you. All it does is help you specify the functions you want to deploy. The body of the function should use the 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(...)
The Admin SDK just wraps the Cloud Firestore Node SDK, so use its reference to navigate the APIs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With