gpt4 book ai didi

node.js - Mongoose 需要一个基于另一个字段的一些枚举值的字段

转载 作者:搜寻专家 更新时间:2023-10-31 22:30:48 26 4
gpt4 key购买 nike

我有一个 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?,
});

感谢您的帮助。

谢谢

最佳答案

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

关于node.js - Mongoose 需要一个基于另一个字段的一些枚举值的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45348331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com