Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

337
Views
Mongoose schema validation when updating the document

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

  • https://mongoosejs.com/docs/faq.html#unique-doesnt-work
  • https://docs.mongodb.com/manual/core/index-unique/
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!