验证猫鼬中的字符串数组

Validate array of strings in mongoose

我想验证请求中的每个字符串数组值。像

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

这是我的架构

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

在我的验证中,我想确保数据库中不存在每封电子邮件。我试过以下方法

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

但问题是如果我尝试 post 数组中的多封电子邮件验证失败并且数据将被插入到数据库中。如何检查其中一封电子邮件是否已存在并拒绝请求?

$in的文档中提到:

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...

所以你可以这样解决:

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