2013-10-30 34 views
19

在我的meteor.js應用程序中,我試圖編寫一個簡單的管理頁面,可以通過他/她的電子郵件地址找到用戶。meteor.js:通過電子郵件找到用戶

我可以看到Meteor.users集合中有一個「郵件」陣列,其中有像這樣

{ address : '[email protected]', 
    verified : false 
} 

通常在MongoDB中我可以在這個「電子郵件」數組內搜索,像這樣的對象:

Meteor.users.find({ emails.address : '[email protected]' }); 

但這查詢拋出一個錯誤:

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

又名流星不喜歡NE sted query ...

有關如何通過電子郵件地址查詢Meteor.users集合的任何想法?

回答

18

電子郵件包含一系列電子郵件。每封郵件都有一個地址。

嘗試{ emails: { $elemMatch: { address: "[email protected]" } } }

關於$elemMatch的信息是here

作爲數組的郵件信息是here

+3

的感謝!這工作完美。奇怪的文檔明確表示$ elemMatch不在客戶端上可用... – Petrov

2

一個可能的解決辦法,如果這個工程的服務器而不是在客戶端上,是使用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', '[email protected]'); 
} 
+0

不要忘記把電子郵件對象放在引號 – Liko

53

您也可以使用你有什麼,只是把它放在引號:

Meteor.users.find({ "emails.address" : '[email protected]' }); 
+5

您可以使用'Meteor.users.findOne',因爲我們正在尋找一個單一的用戶。 – cutemachine

+0

值得注意的是,當有多個電子郵件與提供的電子郵件地址匹配時,Meteor的「Accounts.findUserByEmail(email)」會注意到這一點。 我不知道這是怎麼可能的,除了嚴重的數據庫畸形,但流星似乎認爲這是一個足夠重要的用例來觀察。 https://docs.meteor.com/api/passwords.html#Accounts-findUserByEmail –

3

默認情況下,流星只會發佈登錄用戶,您可以(如您所述)對該用戶運行查詢。爲了訪問其他用戶,你必須把它們發佈在服務器上:

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

並訂閱它們的客戶端上:

Meteor.subscribe('allUsers'); 

,並運行以下命令

Meteor.users.find({"emails": "[email protected]"}).fetch() 

OR

Meteor.users.find({"emails.0": "[email protected]"}).fetch() 

Refer this

+1

我花了這麼長時間試圖弄清楚發生了什麼事情。我是白癡還是真的不那麼清楚? –

+1

並且對不清楚的道歉 - 我的意思是關於「流星只發布登錄用戶,你可以」 - 似乎真的讓人誤解,命名一些'Meteor.users',並且永遠不會比登錄用戶返回更多。 –

3

如果你想在裏面找帳戶陣列中的所有電子郵件,並做了不敏感的查詢:

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