Search code examples
node.jsmongoosemongoose-schema

Mongoose require a field based on some enum values of another field


I have a Mongoose schema Employee. In that I want to store a field (phone number) related to office for the employee, only if he/she is eligible for office, which is only for two levels "senior" and "c-level".

The schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var EmployeeSchema = new Schema({
    name: String,
    designation: String,
    level: {
        type: String,
        enum: ["intern", "junior", "mid-level", "senior", "c-level"],
        required: true,
    },
    phoneNo: { type: String, required: true },
    officePhoneNo: { type: String, required: true } // How to require only if the level is senior or c-level?,
});

Appreciate your help.

Thanks


Solution

  • In Mongoose you can pass a function in required that can return true/false depending on some condition.

    It's also possible to depend required of a field on other fields, which is level in your case. That is, you can optionally required a field. Here's how:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const levels = ["intern", "junior", "mid-level", "senior", "c-level"];
    const levelsEligibleForOffice = ["senior", "c-level"];
    
    var EmployeeSchema = new Schema({
        name: String,
        designation: String,
        level: {type: String, enum: levels, required: true},
        phoneNo: {type: String, required: true},
        officePhoneNo: {type: String, required: isEligibleForOffice}
    });
    
    
    function isEligibleForOffice(){
        if(levelsEligibleForOffice.indexOf(this.level) > -1){  //"this" contains the employee document at the time of required validation
            return true;
        }
        return false;
    }