2016-06-01 94 views
0

我目前正在使用forEach循環遍歷我用來更新和設置/保存我發送的數據的電子郵件數組通過郵寄請求結束。使用forEach循環來保存數據在MongoDB中的數組中的元素

這是我當前的代碼:

app.post('/register/register', function(req, res){ 

var emails = ['[email protected]', '[email protected]', '[email protected]'] 

    emails.forEach(function(element){ 
    User.update(
    {email: element}, {$set: {team: req.body}} 
    , function(err, user){ 
    }) 
    }) 
    res.sendStatus(200); 
}) 

此代碼的工作,但我不禁覺得它真的是寫得不好。在mongoDB中有什麼能夠讓我找到數組電子郵件中的所有文檔,並且可以用數據一次全部更新它,而不是循環遍歷每個項目並以這種方式保存它?

謝謝。

+0

該調用應該是單個更新調用,以減少開銷。在mongoDB端處理數組。我通常將單個項目放入數組中,以便數據庫不必檢查類型 – softwarenewbie7331

回答

1

當然,你可以這樣做:

app.post('/register/register', function(req, res){ 

var emails = ['[email protected]', '[email protected]', '[email protected]'] 

    User.update(
    {email: {$in: emails}}, {$set: {team: req.body}} 
    , function(err, user){ 
    }) 
    res.sendStatus(200); 
}) 

在運營商的$將所有的數組電子郵件中的用戶相匹配。

相關問題