0

Given a model User with the field username is there a way to select all users with a username in an array? I could use a for loop like so to iterate through all the usernames:

var usernamesToFind = ["username", "anotherUsername", "etc"];
for (i = 0; i < usernameToFind.length; i++) {
    User.find({ "username": usernamesToFind[i] }, function(err, foundUser) {
        //notify user they got tagged
    });
}

Is it possible to achieve the result of above loop with one query, where instead of getting username by username, I do one query and get a list of users whose username matched any of the given usernames?

1 Answer 1

1

You can use the $in operator to query, which:

[...] selects the documents where the value of a field equals any value in the specified array.

User.find({ username: { $in: usernamesToFind } }, function(err, foundUser) {
  //...
});
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.