Mongoose需要基于另一个字段的某些枚举值的字段

时间:2017-07-27 10:36:13

标签: node.js mongoose mongoose-schema

我有一个Mongoose架构Employee。在那里我想存储一个与办公室相关的领域(电话号码)给员工,只要他/她有资格上任,这只是两个级别"高级"和" c-level"。

架构:

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?,

});

感谢您的帮助。

由于

1 个答案:

答案 0 :(得分:7)

在Mongoose中,您可以传递required中可以返回true/false的函数,具体取决于某些条件。

还可以在其他字段中依赖required字段,在您的情况下为level。也就是说,您可以选择需要一个字段。以下是:

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