Search code examples
mongodbexpressmongooseexpress-validator

Validate array of strings in mongoose


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

emails: [ 'johndoe@gmail.com', 'jandoe@gmail.com' ]

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?


Solution

  • 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 },
    })...