Home > other >  Firebase db is not defined on HTTPS Firebase Function
Firebase db is not defined on HTTPS Firebase Function

Time:01-11

I am creating a Firebase HTTPS function that reads data from Firestore and returns to the user.

However, I get 'db is not defined'. I've tried different ways of writing this such as const db = firebase.firestore(); but this causes an error TypeError: firestore.firestore is not a function

Here is the code I've written

const functions = require("firebase-functions");
const admin = require('firebase-admin');
const { firestore } = require("firebase-admin");

admin.initializeApp();

const db = firestore.firestore();


exports.getUsers = functions.https.onRequest((request, response) => {
  let user = request.query.user;
  let ids = getIdsOfUsersWhoHaveSeenUser(user);
  let jsonBody = {
    "users": ids
  }
  let responseBody = JSON.stringify(jsonBody);
  response.send(responseBody);
});

function getIdsOfUsersWhoHaveSeenUser(user) {
  const query = db.collection('users').whereField('seenUsers', arrayContains(user));
  query.get()
    .then(snapshot => {
      const documents = snapshot.docs;
      const ids = documents.map(doc => doc.id);
      return ids;
    })
    .catch (error => {
      console.log(error);
    });
};

I've also tried admin.firestore().collection() but that doesn't work either.

CodePudding user response:

You should do as follows:

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

admin.initializeApp();

const db = admin.firestore();

admin is the admin app instance from which Cloud Firestore changes can be made.


In addition you need to:

  1. Correctly return the Promise chain in your getIdsOfUsersWhoHaveSeenUser function
  2. Note that whereField() is not a method of the Admin SDK. You should use the where() method, see the doc.

function getIdsOfUsersWhoHaveSeenUser(user) {
  const query = db.collection('users').where("seenUsers", "array-contains", "user");  // <== See change here

  return query.get()   // <== See return here
    .then(snapshot => {
      const documents = snapshot.docs;
      const ids = documents.map(doc => doc.id);
      return ids;
    })
    .catch (error => {
      console.log(error);
    });
};

and also take into account the fact that this getIdsOfUsersWhoHaveSeenUser function is asynchronous.

exports.getUsers = functions.https.onRequest((request, response) => {
  let user = request.query.user;
  getIdsOfUsersWhoHaveSeenUser(user)
 .then(ids => {
    let jsonBody = {
       "users": ids
    }
    let responseBody = JSON.stringify(jsonBody);
    response.send(responseBody);

  });
});
  • Related