繁体   English   中英

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

[英]Firebase check if node exist return true or false

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

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

我创建了 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。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM