0

I'm currently using a forEach loop that iterates through an array of emails that I'm using to update and set/save the data that I'm sending over via a post request.

This is my current code:

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

This code works but I can't help but feel that it is really poorly written. Is there something in mongoDB that will allow me to find all the documents in the array emails and I can update it all at once with the data instead of looping through each item and saving it that way?

Thank you.

1
  • the call should be a single update call, to reduce overheads. handle the array at the mongoDB side. I usually put single items into an array anyway so that the DB doesn't have to check type Commented Jun 1, 2016 at 1:50

1 Answer 1

1

Sure, you can do this:

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

The $in operator will match all the users with emails in your array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.