JohnSan
JohnSan

Reputation: 53

Cloud functions error : TypeError: db.collection is not a function

When trying to send the data to the firestore, you are returning this error:

TypeError: db.collection is not a function
    at FirestoreHelper.updateDocument (/workspace/node_modules/firebase-functions-helper/dist/firestore.js:7:56)
    at app.patch (/workspace/lib/index.js:20:40)
    at Layer.handle [as handle_request] (/workspace/node_modules/express/lib/router/layer.js:95:5)
    at next (/workspace/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/workspace/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/workspace/node_modules/express/lib/router/layer.js:95:5)

My index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as firebaseHelper from 'firebase-functions-helper/dist';
import * as express from 'express';
import * as bodyParser from 'body-parser';

admin.initializeApp(functions.config().firebase);
const db = admin.firestore;

const app = express();
const main = express();

main.use(bodyParser.json());
main.use(bodyParser.urlencoded({extended: false}));
main.use('/api/v1', app);

const trackerCollection = 'tracker';
export const webApi = functions.https.onRequest(main);

app.patch('/trackers/:trackerId', async(req, res) => {
    try {
        await firebaseHelper.firestore.updateDocument(db, trackerCollection, req.params.trackerId, req.body);
        res.status(200).send('Update Success');
    } catch (error) {
        console.log(error);
        res.status(204).send('Patch Error');
    }
})

I'm auditioning for the postman. The api url is: https: //myapp.../api/v1/trackers/12345678

Status postman = 204

My collection in firestore: enter image description here

Upvotes: 0

Views: 407

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

You need to do

const db = admin.firestore();

instead of

const db = admin.firestore;

Also note that, since Version 1.0.0 of the Firebase SDK for Cloud Functions, firebase-admin shall be initialized without any parameters, see https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin.

Upvotes: 1

Related Questions