Javascript Firebase .orderByChild().equalTo().once().then() 当孩子不存在时承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39176070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:18:41  来源:igfitidea点击:

Firebase .orderByChild().equalTo().once().then() Promises when child doesn't exist

javascriptnode.jsfirebasepromisefirebase-realtime-database

提问by Jacob

My API /auth/loginendpoint takes a req.bodylike this:

我的 API/auth/login端点是req.body这样的:

{
  "email": "[email protected]",
  "password": "supersecretpassword"
}

At the endpoint, I make a reference to my Firebase database (https://jacob.firebaseio.com/users). I search through the data, and when I find one user with the email that matches req.body.email, I compare the password with the one stored in the database.

在端点,我引用了我的 Firebase 数据库 ( https://jacob.firebaseio.com/users)。我搜索数据,当我找到一个电子邮件匹配的用户时req.body.email,我将密码与数据库中存储的密码进行比较。

I followed the promise structure outlined in this Firebase blog post.

我遵循了这篇 Firebase 博客文章中概述的承诺结构。

router.post('/login', function(req, res) {
  const ref = db.ref('/users');

  ref.orderByChild('email')
    .equalTo(req.body.email)
    .once('child_added')
    .then(function (snapshot) {
      return snapshot.val();
    })
    .then(function (usr) {

      // Do my thing, throw any errors that come up

    })
    .catch(function (err) {

      // Handle my errors with grace

      return;
    });
});

If no child is found at ref, the function does not proceed (see this answer). I don't even get an error thrown.

如果在 处未找到子项ref,则该函数不会继续执行(请参阅此答案)。我什至没有抛出错误。

My goal is to run code when no user is found with a certain email (i.e. no child is found at refthat satisfies .equalTo(req.body.email)), but not run the code if a user is found. No error is thrown when nothing is found.

我的目标是在没有找到某个电子邮件的用户时运行代码(即没有找到ref满足的孩子.equalTo(req.body.email)),但如果找到用户则不运行代码。当什么都没有找到时,不会抛出任何错误。

I tried adding returnstatements at strategic points in the call to the database (at the end of my .then()promises) with the intention of breaking out of the endpoint entirely after the code was run. I then put code after the call to the database:

我尝试return在调用数据库的战略点(在我的.then()承诺结束时)添加语句,目的是在代码运行后完全脱离端点。然后我在调用数据库后放置代码:

    .then(function (usr) {

      // Do my thing, throw any errors that come up

    })
    .catch(function (err) {

      // Handle my errors with grace

      return;
    });

  res.status(401)
    .json({
      error: 'No user found',
    )};

  return;
});

but this code is run whether the call to the database succeeds or not, since the call is asynchronous.

但是无论对数据库的调用成功与否,此代码都会运行,因为调用是异步的。

How do I react to this call to the database if it doesn't return anything andstill use Firebase promises?

如果它不返回任何内容并且仍然使用 Firebase 承诺,我该如何响应对数据库的调用?

回答by cartant

The child_addedevent only fires if the query matches at least one of the keys under usersand will fire multiple times if there are multiple matches.

child_added事件仅在查询匹配至少一个下面的键时users才会触发,如果有多个匹配项,则会触发多次。

You can use the valueevent instead - it will fire only once and its snapshot will contain all of the keys under usersthat matched or will have valueof nullif there are no matches:

您可以使用value事件,而不是-它会火只有一次,它的快照将包含所有的下键users匹配或会有valuenull,如果没有匹配:

router.post('/login', function(req, res) {
  const ref = db.ref('/users');

  ref.orderByChild('email')
    .equalTo(req.body.email)
    .once('value')
    .then(function (snapshot) {
      var value = snapshot.val();
      if (value) {
        // value is an object containing one or more of the users that matched your email query
        // choose a user and do something with it
      } else {
        res.status(401)
          .json({
            error: 'No user found',
          )};
      }
    });
});

Regarding handling of errors, you can wire up the promise and express error handling like this:

关于错误的处理,你可以像这样连接 promise 并表达错误处理:

router.post('/login', function(req, res, next) {
  const ref = db.ref('/users');

  ref.orderByChild('email')
    .equalTo(req.body.email)
    .once('value')
    .then(function (snapshot) {
      ...
    })
    .catch(next);
});