我有一个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?,
});
感谢您的帮助。
由于
答案 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;
}