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

73
Visualizações
How to make sure that only one of two fields are populated in mongoDB

I am using mongoose as an ODM and trying to model an animal/pet. In the model I have 2 fields, parent and shelter. I want to make sure that pet belongs to a person or a shelter but not both. What constraints would allow me to do this.

My model in JS:-

const petSchema = mongoose.Schema({
    name: { 
        type: String,
        required: [true, "Pet must have a name."],
        trim: true
    },
    species: {
        type: String,
        required: [true, "Pet must have a species."]
    },
    parent: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    shelter: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Shelter'
    }
}

I am new to databases and their jargons, correct me if any error in question. Thank you.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use the required function to determine this as follows:

const petSchema = mongoose.Schema({
    name: { 
        type: String,
        required: [true, "Pet must have a name."],
        trim: true
    },
    species: {
        type: String,
        required: [true, "Pet must have a species."]
    },
    parent: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: function() {
          return !this.shelter;
        }
    },
    shelter: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Shelter',
        required: function() {
          return !this.parent;
        }
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

I ended up using pre validate middleware in mongoose:-

petSchema.pre('validate', function (next) {
    if((this.parent && this.shelter) || (!this.parent && !this.shelter))
        return next(new Error("At least and Only one field(parent, shelter) should be populated"))
    next()
})
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