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

70
Views
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 answers
Answer question

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 Report

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 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!