Search code examples
mongodbexpressmongooseexpress-validator

Validate unique text using Express Validator & Mongoose


I have a mongodb collections named "articles"

I have configured below rules for validating "title" field of article while Updating the record.

validator.body('title').custom( (value, {req}) => {
    console.log(value, req.params.id)
    return Article.find({ title:value, _id:{ $ne: req.params.id } })
      .then( article => {
      if (article) {
        return Promise.reject('Title already in use');
      }
    })
  })

So basically it should check if "title" should not exists in the collection and it should not be the same ID as the one I am updating.

The line console.log(value, req.params.id) is printing proper Title and ID but the validation is always saying "Title already in use". Even though I use entirely different title that is not used at all.

Any idea what's wrong?


Solution

  • You should use findOne query for better performance and check data is null like as bellow.

    validator.body('title').custom( (value, {req}) => {
        console.log(value, req.params.id)
        return Article.findOne({ title:value, _id:{ $ne: req.params.id } })
          .then( article => {
          if (article !== null) {
            return Promise.reject('Title already in use');
          }
        })
      })