ninj4 n00b
ninj4 n00b

Reputation: 1233

admin.firestore is not a function when trying to use google cloud functions with node.js

This is the header of the node.js index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();

This is the node.js function to listen to firestore changes:

exports.myFoo = functions.firestore
  .document('foo/{bar}')
  .onWrite(event => {
    // do stuff
}

This is in the package.json file:

  "dependencies": {
    "firebase-admin": "^5-.4.2",
    "firebase-functions": "^0.7.1",
    "firestore": "^1.1.6"
  },

When I try to do a "firebase deploy" command this is the error I am getting:

Error: Error occurred while parsing your function triggers.
TypeError: admin.firestore is not a function

askFirebase

Upvotes: 20

Views: 9122

Answers (4)

B. Chandresh
B. Chandresh

Reputation: 125

Try this

const getReceiverDataPromise = admin.firestore().doc('users/' + receiverUID).get();
const getSenderDataPromise = admin.firestore().doc('users/' + senderUID).get();

return Promise.all([getReceiverDataPromise, getSenderDataPromise]).then(results => {

        const receiver = results[0].data();
        console.log("receiver: ", receiver);

        const sender = results[1].data();
        console.log("sender: ", sender);

    });

Upvotes: 1

Martin
Martin

Reputation: 650

functions.firestore is supposed to be functions.firestore()

Upvotes: 0

Charles Romney
Charles Romney

Reputation: 27

To solve in your file.js (async method) :

const getFirestore = () => admin.firestore()

exemple :

 getFirestore()
  .collection(`mailchimp-users`)
  .doc(uid)
    .set(profile)
      .then(() => res.redirect(MAILCHIMP_AUTH_SUCCESS_URL))
      .catch((error) => res.json({error}))

Upvotes: -2

Bob Snyder
Bob Snyder

Reputation: 38289

I was able to reproduce the error and brute-force a solution. I don't know much about npm and can't offer a complete explanation of why this solution worked.

My original package.json contained:

  "dependencies": {
    ...
    "firebase-admin": "^4.2.1",
    "firebase-functions": "^0.7.1",
    ...
  },

As recommended in the documentation, I ran these two commands in the functions folder:

npm install -g firebase-tools
npm install firebase-functions@latest --save

I also tried:

npm install --save firebase-admin
npm upgrade

I repeatedly received these error messages:

+-- UNMET PEER DEPENDENCY [email protected]
npm WARN [email protected] requires a peer of firebase-admin@~5.4.2 but none was installed.

I figured firebase-admin needed to be updated but couldn't make it happen. So I edited the dependencies file to delete this line:

"firebase-admin": "^4.2.1"

then ran npm install --save firebase-admin again. With that, the package.json contained version "firebase-admin": "^5.4.2" and var db = admin.firestore(); compiled without error.

Upvotes: 16

Related Questions