【问题标题】:Firebase check if node exist return true or falseFirebase 检查节点是否存在返回 true 或 false
【发布时间】:2020-03-23 23:36:51
【问题描述】:

我有这个 firebase 实时数据库:

我正在为我的单身汉制作约会应用程序,类似于 tinder。我现在正在创建匹配系统。

我创建了 onCreate 监听器来检查用户何时按下like 按钮并检查其他用户是否已经按下了当前用户的like。所以这就是我尝试过的。

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。

【问题讨论】:

  • 目前您的问题非常广泛。特别关注您遇到的问题。你试过什么?是什么不工作。

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


【解决方案1】:

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

要调用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 的更多信息之前,我强烈建议您不要继续。例如,通过观看 Doug 的视频系列Learn JavaScript Promises with HTTP Triggers in Cloud Functions

【讨论】:

  • 非常感谢,我在 Google 上搜索了 async/await,然后看到了您的评论。感谢您的内容。
【解决方案2】:

做完Puf的修复后,可以查看snapshot.val() !== null,或者使用快捷键snapshot.exists()

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

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多