Was*_*Ali 6 mongoose node.js mongoose-schema
我有一个Mongoose架构Employee.在此我想存储与办公室员工的字段(电话号码),只有当他/她可享有办公室,里面只有两个层次"高级"和"C级".
架构:
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?,
});
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助.
谢谢
在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1365 次 |
| 最近记录: |