Search code examples
node.jsgoogle-cloud-firestoregoogle-cloud-functionsfirebase-admin

Firebase functions db.doc is not a function, Error when im trying to create a new collection with a document


Hi I was following a youtube tutorial (https://www.youtube.com/watch?v=m_u6P5k0vP0&t) for some work i was doing and came across this error when i tried to create a new collection with a new doc after a new doc was created on the like collection

Image with the error on firebase [1]: https://i.sstatic.net/sixMc.png

The function was supposed to create a notification collection with a document when someone liked a post.

-------------admin.js--------------

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

admin.initializeApp();

const db = admin.firestore();

module.exports = { admin ,db}; 

------------index.js---------------

const db = require('./util/admin');


exports.createNotificationOnLike = functions
  .firestore.document('likes/{id}')
  .onCreate((snapshot) => {
    return db
      .doc(`/screams/${snapshot.data().screamId}`)
      .get()
      .then((doc) => {
        if (
          doc.exists &&
          doc.data().userHandle !== snapshot.data().userHandle
        ) {
          return db.doc(`/notifications/${snapshot.id}`).set({
            createdAt: new Date().toISOString(),
            recipient: doc.data().userHandle,
            sender: snapshot.data().userHandle,
            type: 'like',
            read: false,
            screamId: doc.id
          });
        }
      })
      .catch((err) => console.error(err));
  });

Solution

  • Your syntax for requiring admin.js is not correct. It's exporting an object with two properties, not just db, so you need to say that you are expecting an object with a property called db.

    const [ db } = require('./util/admin');