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

111
Visualizações
Mongoose allow a key to exist only if another is set to a certain value

I have a collection which describes requests. It looks like this:

const requestSchema = mongoose.Schema({
  status: {
    type: String,
    required: true,
    enum: ["available", "failed", "succeed"],
  },
  errorCode: { type: String , required : (when status is failed)},
});

My goal is to require errorCode only if status is set to 'failed' and don't allow it to exist otherwise. And if possible to have it removed when status is changed to 'succeed' for example. I can't quite find an answer anywhere.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could pass a function to required to make errorCode required only if status is equal to "failed", like so:

const requestSchema = mongoose.Schema({
  status: {
    type: String,
    required: true,
    enum: ["available", "failed", "succeed"],
  },
  errorCode: {
    type: String,
    required: function () {
      return this.status === "failed";
    },
  },
});

To remove it when status changes to "succeed", or to any other value than "failed", you can use pre method, like so:

requestSchema.pre("save", async function (next) {
  if (this.status !== "failed") { // change it as you want
    this.errorCode = "";
  }
  next();
});
about 4 years ago · Juan Pablo Isaza 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