【问题标题】:meteor.js : find users by emailmeteor.js : 通过电子邮件查找用户
【发布时间】:2013-11-10 19:18:57
【问题描述】:

在我的 meteor.js 应用程序中,我正在尝试编写一个简单的管理页面,可以通过他/她的电子邮件地址找到用户。

我可以看到在 Meteor.users 集合中有一个 'emails' 数组,其中有这样的对象

{ address : 'foo@foo.com',
  verified : false
}

通常在 Mongodb 中,我可以像这样在这个“电子邮件”数组中搜索:

Meteor.users.find({ emails.address : 'foo@foo.com' });

但是这个查询抛出了一个错误:

While building the application:
client/admin.js:224:41: Unexpected token .

Aka Meteor 不喜欢嵌套查询...

关于如何通过电子邮件地址查询 Meteor.users 集合的任何想法?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您也可以使用已有的,只需将其放在引号中即可:

    Meteor.users.find({ "emails.address" : 'foo@foo.com' });
    

    【讨论】:

    • 您可以使用Meteor.users.findOne,因为我们正在寻找一位用户。
    • 值得注意的是,Meteor 的Accounts.findUserByEmail(email) 会在有多个电子邮件与提供的电子邮件地址匹配时引起注意。我不知道这是怎么可能的,除了严重的数据库畸形,但 Meteor 似乎认为这是一个值得关注的重要用例。 docs.meteor.com/api/passwords.html#Accounts-findUserByEmail
    • 此解决方案不考虑潜在的大小写不匹配。 Accounts.findUserByEmail(email) 可以。
    【解决方案2】:

    如果在服务器上,Meteor 有一个特殊的功能: Accounts.findUserByEmail(email)

    我相信这是推荐的方式。

    【讨论】:

      【解决方案3】:

      Emails 包含一系列电子邮件。每封电子邮件都有一个地址。

      试试{ emails: { $elemMatch: { address: "foo@foo.com" } } }

      $elemMatch 上的信息是here

      关于电子邮件的数组信息是here

      【讨论】:

      • 谢谢!这工作得很好。奇怪的是,文档明确说 $elemMatch 在客户端上不可用...
      【解决方案4】:

      默认情况下,Meteor 只发布登录用户,正如你提到的,你可以对该用户运行查询。为了访问其他用户,您必须在服务器上发布他们:

      Meteor.publish("allUsers", function () {
        return Meteor.users.find({});
      });
      

      并在客户端订阅它们:

      Meteor.subscribe('allUsers');
      

      并运行以下命令

      Meteor.users.find({"emails": "me@example.com"}).fetch()
      

      Meteor.users.find({"emails.0": "me@example.com"}).fetch()
      

      Refer this

      【讨论】:

      • 我花了很长时间试图弄清楚发生了什么。我是白痴还是真的没那么清楚?
      • 抱歉不清楚 - 我的意思是“Meteor 只发布登录用户,你可以” - 命名 Meteor.users 并让它永远不会返回超过登录的用户似乎真的很误导用户。
      【解决方案5】:

      如果您想在 Accounts 数组中查找所有电子邮件,并进行不敏感查询:

      const hasUser = Meteor.users.findOne({
          emails: {
            $elemMatch: {
              address: {
                $regex : new RegExp(doc.email, "i")
              }
            }
          }
      });
      

      【讨论】:

        【解决方案6】:

        一种可能的解决方法是,如果这适用于服务器而不是客户端,则在服务器上使用users_by_email 方法:

        if (Meteor.isServer) {
            Meteor.methods({
                'get_users_by_email': function(email) {
                    return Users.find({ emails.address: email }).fetch();
                }
            });
        }
        if (Meteor.isClient) {
            foo_users = Meteor.call('get_users_by_email', 'foo@bar.baz');
        }
        

        【讨论】:

        • 不要忘记将电子邮件对象放在引号中
        猜你喜欢
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        • 1970-01-01
        • 2018-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多