【问题标题】:Why is my function not reaching this forEach loop?为什么我的函数没有达到这个 forEach 循环?
【发布时间】:2021-05-19 23:46:38
【问题描述】:

我试图在用户注册时添加到我的 firestore 数据库,但由于某种原因,代码根本没有到达 forEach 循环。我已经尝试添加一堆日志记录,如下所示。日志显示它到达了console.log('_createUser: 1.1');,但它从未到达console.log('_createUser: 2');。为什么不执行 forEach 循环?

注意 - 函数以状态码 200 结束。

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
// import { error } from 'firebase-functions/lib/logger';
admin.initializeApp();

exports.createUser = functions.https.onCall(async (data, context) => {
  console.log('_createUser: ');
  const uid = context?.auth?.uid;
  if (uid) {
    const username = data.user;
    const email = data.email;
    console.log('_createUser: 1');
    //Check to see if that username already exists
    const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get();
    console.log('_createUser: 1.1');
    qData.forEach(doc => {
      console.log('_createUser: 2');
      const otherUsername = doc.get('username').toString();      
      if (otherUsername) {
        console.log('_createUser: Username is already in use.');
        return 'Username is already in use.'
      }
      else {
        console.log('_createUser: 3');
        //Create collection for this user's friends list
        const friendsColl = 'friends_' + uid;
        const friendsDoc = admin.firestore().collection(friendsColl).doc();
        friendsDoc.set({
          //Forces the collection to exist
          exists: 1, 

          //Other useful data
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          ownerUsername: username,
          ownerUID: uid, //
          rowType: 'B', //N = normal, B = backend (created for server side reasons)
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        console.log('_createUser: 4');
        const userDoc = admin.firestore().collection('users').doc(uid); // use uid as document ID
        userDoc.set({
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          username: username,
          email: email,
          stat: 1, //0 = banned, 1 = normal
          uid: uid,
          friendsColl: friendsColl,
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        return console.log('_createUser_finished');
      };
    });    
  }
  else {
    return console.log('_createUser_Error: User is not authorized');
  };
});

【问题讨论】:

  • 控制台有错误吗?另外,记录数组并确保它不为空
  • @AluanHaddad 控制台中没有错误。我想我应该提到const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get(); 不会返回任何行,因为我尝试注册的用户名肯定不存在。之前,我设置了它,以便它检查 qData 是否存在,但它返回 true,所以我简单地删除了它。

标签: javascript typescript google-cloud-firestore google-cloud-functions


【解决方案1】:

qData 对象是 QuerySnapshot。可以从docs 属性访问查询返回的文档。因此,您需要将qData.forEach(doc => { 更新为qData.docs.forEach(doc => {

只是好奇,为什么不为此使用 Firebase 身份验证触发功能?您可以编写一个在每次创建用户时都会运行的函数,而无需您自己做任何事情。看看this

【讨论】:

  • 这样做与使用身份验证触发器有区别吗?
  • 实际上,您可以使用任一解决方案获得相同的结果。但是使用身份验证触发器更有意义,因为您希望在用户注册时运行此功能。您不必检查授权,也不必使用 Firestore 读取。我认为主要的好处是它会自动运行,而不是依赖于外部调用。
  • 啊,我正在使用客户端 firebase.auth 将电子邮件和密码安全地传递给服务器。在传递给后端以在那里运行身份验证触发器之前,我不确定如何加密此信息。
  • 您无需担心触发器功能的身份验证。他们与客户完全绝缘。如果您将此 onCall 函数重写为触发函数,它将不会进行第一次 if 检查,并且您将从传递给处理程序的 UserRecord 对象中获取用户详细信息(因此也不会读取 Firestore)。
【解决方案2】:

因为你没有解决 Promise。使用这种格式。

qData.then(snap => {
  snap.forEach(doc=>{
  ...
  })
})

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
// import { error } from 'firebase-functions/lib/logger';
admin.initializeApp();

exports.createUser = functions.https.onCall(async (data, context) => {
  console.log('_createUser: ');
  const uid = context?.auth?.uid;
  if (!uid) {
    console.log('_createUser_Error: User is not authorized');
    return 
  }
  const username = data.user;
  const email = data.email;
  console.log('_createUser: 1');
  //Check to see if that username already exists
  const qData = await admin.firestore().collection('users').where('username', '==', username).limit(1).get();
  console.log('_createUser: 1.1');
  qData.then(snapShot => {
    snapShot.forEach(doc => {
      console.log('_createUser: 2');
      const otherUsername = doc.get('username').toString();      
      if (otherUsername) {
        console.log('_createUser: Username is already in use.');
        return 'Username is already in use.'
      }
      else {
        console.log('_createUser: 3');
        //Create collection for this user's friends list
        const friendsColl = 'friends_' + uid;
        const friendsDoc = admin.firestore().collection(friendsColl).doc();
        friendsDoc.set({
          //Forces the collection to exist
          exists: 1, 

          //Other useful data
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          ownerUsername: username,
          ownerUID: uid, //
          rowType: 'B', //N = normal, B = backend (created for server side reasons)
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        console.log('_createUser: 4');
        const userDoc = admin.firestore().collection('users').doc(uid); // use uid as document ID
        userDoc.set({
          createDate: admin.firestore.FieldValue.serverTimestamp(),
          modifiedDate: admin.firestore.FieldValue.serverTimestamp(),
          username: username,
          email: email,
          stat: 1, //0 = banned, 1 = normal
          uid: uid,
          friendsColl: friendsColl,
        })
        .then(() => {
          console.log("Document successfully written!");
        })
        .catch((error) => {
          console.error("Error writing document: ", error);
        });
        return console.log('_createUser_finished');
      };
    })
  })
})

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 2015-02-06
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多