aslamdoctor
aslamdoctor

Reputation: 3935

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?

Upvotes: 0

Views: 1149

Answers (2)

laxman
laxman

Reputation: 1348

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');
      }
    })
  })

Upvotes: 3

aslamdoctor
aslamdoctor

Reputation: 3935

Stupid mistake,

the

if (article) {

is supposed to be

if (article.length) {

And it worked fine.

Upvotes: 0

Related Questions