Home > Blockchain >  How to make sure that only one of two fields are populated in mongoDB
How to make sure that only one of two fields are populated in mongoDB

Time:02-16

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.

CodePudding user response:

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;
        }
    }
}
  • Related