1

Hello, I have a mongoose schema for a slug. I want to check uniqueness of it

slug: {
  type: String,
  default: "",
  trim: true,
  validate: {
    validator: async function (value) {
      const user = await this.model.findOne({ slug: value });
      console.log(user);
      console.log(this);
      if (user) {
        if (this.id === user.id) {
          return true;
        }
        return false;
      }
      return true;
    },
    message: (props) => "This slug is already in use",
  },
},

this validation is working fine when inserting a new document but in updating case, I want to compare it with all other fields in the schema other than itself. how could I do that

I have also added runValidators to check validation when updating also

CMS.pre("findOneAndUpdate", function () {
  this.options.runValidators = true; 
});

if you can suggest a better way of checking slug uniqueness in mongoose when inserting and updating

Thanks in advance

swapnil gautam
  • 319
  • 2
  • 9
  • What's wrong with this way? Are you running into any issues? – Tom Dec 10 '21 at 11:08
  • when inserting it works fine, but when updating it compare slug with the current document also which I am trying updating, and gives the validation error, a want to skip the current document and compare it with others only – swapnil gautam Dec 10 '21 at 11:15

1 Answers1

2

Why are you using a validator? Why not just ensure that the slug is unique by defining an index?

const User = new Schema({
    slug: {
        type: String,
        default: "",
        trim: true,
        unique: true,
    }
});

You will need to catch the error though when attempting to insert an already existing user, since the the unique option is not a validator. See: How to catch the error when inserting a MongoDB document which violates an unique index?

Reference:

Tom
  • 4,070
  • 4
  • 22
  • 50
  • yes that is correct, but if I want to use a validator for another purpose also, Is there is any way I can get the current document and updated document so I can compare their id or something – swapnil gautam Dec 10 '21 at 11:47
  • That wasn't part of your original question. I'd suggest you create the index using `unique` and then add an extra validator. To compare documents, you could use a hook that fires prior to saving/updating: [mogoose docs](https://mongoosejs.com/docs/api.html#schema_Schema-pre). Hooks are fired after `validate. See: [mongoose-difference-between-pre-save-and-validate-when-to-use-which-one](https://stackoverflow.com/questions/31471940/mongoose-difference-between-pre-save-and-validate-when-to-use-which-one). I suggest that you make your self more familiar with how mongoose works. – Tom Dec 13 '21 at 08:44