Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

344
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda