Validate array of strings in mongoose

695 views Asked by At

I wanted to validate each value from the request which is array of strings. Something like

emails: [ '[email protected]', '[email protected]' ]

Here is my schema

const UserSchema = mongoose.Schema({
  name: {
    type: String,
    index: true,
    required: true,
  },
  emails: [String],
});

In my validation I wanted to make sure that each email is not already exists in the database. I've tried the following

body("emails").custom((value, { req }) => {
  return User.findOne({
    emails: { $all: value },
    _id: { $ne: req.params.id },
  }).then((exists) => {
    if (exists) {
      return Promise.reject("Email already exists!");
    }
  });
});

But the problem is if I tried to post multiple emails in array the validation fails and the data will be inserted to db. How can I check if one of the emails already exists and reject the request?

1

There are 1 answers

1
Cuong Le Ngoc On BEST ANSWER

In the docs of $in, it mentioned that:

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array...

So you can solve it by:

User.findOne({
  emails: { $in: value },
  _id: { $ne: req.params.id },
})...