未在HTTPS Firebase函数上定义Firebase数据库

izkcnapc  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在创建一个Firebase HTTPS函数,该函数从Firestore读取数据并返回给用户。
但是,我得到了“db is not defined”。我尝试了不同的编写方法,例如const db = firebase.firestore();,但这会导致错误TypeError: firestore.firestore is not a function
下面是我编写的代码

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);
    });
};

我也试过admin.firestore().collection(),但也不起作用。

8oomwypt

8oomwypt1#

您应该执行以下操作:

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

admin.initializeApp();

const db = admin.firestore();

admin是管理应用程序示例,可从中进行Cloud Firestore更改。
此外,您还需要:
1.在getIdsOfUsersWhoHaveSeenUser函数中正确返回Promise链
1.注意whereField()不是Admin SDK的方法,您应该使用where()方法,请参阅文档。

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);
    });
};

并且还考虑了该getIdsOfUsersWhoHaveSeenUser函数是异步的事实。

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);

  });
});

相关问题