node.js - mongoose Schema 中的验证
问题描述
我正在为猫鼬中的用户模式条目编写验证。我想在架构中创建两个条目(密码、googleId)中的任何一个,但不是两个条目都是必需的。我想确保用户有密码或 googleId。如何做到这一点?以下是我的架构
const UserSchema = new mongoose.Schema({
password: {
type: String,
trim: true,
required: true,
validate: (value)=>
{
if(value.includes(this.uname))
{
throw new Error("Password must not contain username")
}
}
},
googleId: {
type: String,
required: true
}
});
解决方案
您可能会做的是添加一个预验证检查,然后调用 next 或使文档无效。
const schema = new mongoose.Schema({
password: {
type: String,
trim: true
},
googleId: {
type: String
}
});
schema.pre('validate', { document: true }, function(next){
if (!this.password || !this.googleId)
this.invalidate('passwordgoogleId'. 'One of the fields required.');
else
next();
});
我还没有尝试过。
推荐阅读
- opengl - 如何将抗锯齿图像渲染到纹理(然后写入 PNG)?
- database - Oracle SQL 不同环境下相同查询的不同计划
- bash - 在詹金斯管道中使用时出现 jq 问题
- php - PHPDoc 将@param 分配为引用的@property
- github - 如何重新运行使用 culebra 测试器记录的 java (UI automator/python) 脚本
- react-redux - 在哪里可以找到关于登台/生产的后端打印输出?
- hive - 在 hive 中将字符串转换为日期
- assembly - 为什么添加 3 BYTE 失败,但 DWORD 成功
- java-8 - 如何从 kotlin 传递供应商?
- linux - 为什么两个进程都盯着一个 java 命令