简体   繁体   中英

Firebase check if node exist return true or false

I have this firebase realtime database: Firebase 树

I am making dating app, similar to tinder for my bachelor. I am creating match system now.

I created onCreate listener to check when the user presses like button and to check if another user already pressed like on current user. So this is what i tried.

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

I want checkUserMatch to return true if there is that node, and false if there is no such node.

Your checkUserMatch is asynchronous (as shown by the fact you marked it with async ), which means that it doesn't immediately return a value, but return an object that will eventually contain a value (a so-called promise).

To call an async function, you need to call it with await :

const a = await checkUserMatch(userId, matchedUserId);

This means that you also need to mark the function containing the call as async , so:

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

Note that I highly recommend not continuing before you've learned more about asynchronous APIs, Promises and async / await . For example, by watching Doug's video series Learn JavaScript Promises with HTTP Triggers in Cloud Functions .

After doing Puf's fix, you can check if snapshot.val() !== null , or use the shortcut snapshot.exists() .

And you better rename your const snapshot to const isLiked , and then actually return that isLiked (or that function will return undefined ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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