Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 402
Wasif Ali Avatar asked Jul 27 '17 10:07

Wasif Ali


Video Answer


1 Answers

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;
}
like image 170
Talha Awan Avatar answered Oct 26 '22 17:10

Talha Awan