Firebase检查节点是否存在,返回true或false

时间:2020-03-23 10:50:43

标签: javascript firebase firebase-realtime-database google-cloud-functions

我有这个firebase实时数据库: Firebase tree

我正在制作约会应用程序,类似于单身汉的火种。我正在创建比赛系统。

我创建了onCreate侦听器,以检查用户何时按赞按钮,并检查是否有另一个用户像当前用户一样按了按钮。所以这就是我尝试过的。

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate((snapshot, context) => {
    // Grab the current value of what was written to the Realtime Database.
    const original = snapshot.val();
    const userId = context.params.userId;
    const matchedUserId = context.params.otherUserId;
    const a = checkUserMatch(userId, matchedUserId);
    if (a === true) {
      console.log('Its a match');
    } else {
      console.log('There is no match');
      console.log(a);
    }

    return null;
  });

checkUserMatch = async (userId, matchedUserId) => {
  const snapshot = await admin
    .database()
    .ref('/users/' + matchedUserId + '/matches/' + userId)
    .once('value')
    .then(snapshot => {
      // let tempuserId = snapshot.val();
      // if()
      return true;
    });
};

我希望checkUserMatch如果有该节点,则返回true,如果没有该节点,则返回false。

2 个答案:

答案 0 :(得分:2)

您的checkUserMatch是异步的(如您用async标记的事实所示),这意味着它不会立即返回值,而是返回最终将包含值的对象(所谓的承诺)。

要调用async函数,您需要使用await进行调用:

const a = await checkUserMatch(userId, matchedUserId);

这意味着您还需要将包含调用的函数标记为async,因此:

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate(async (snapshot, context) => {

请注意,在您进一步了解异步API,Promises和async / await之前,我强烈建议您不要继续。例如,通过观看道格的视频系列Learn JavaScript Promises with HTTP Triggers in Cloud Functions

答案 1 :(得分:1)

修复Puf后,您可以检查是否snapshot.val() !== null,或使用快捷方式snapshot.exists()

最好将const snapshot重命名为const isLiked,然后实际返回该isLiked(否则该函数将返回undefined)。