mongoose - 属性为空时如何触发猫鼬默认值
问题描述
在我的架构中,我为属性定义了一个默认值:
const patientSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
lastName: {type : String, required: true},
firstName: {type : String, required: true},
phone: String,
mobile: String,
email: String,
subscriptionDate: {type : Date, default: Date.now}
});
我希望在传递的值为空时使用它。我知道它只有在它未定义的情况下才有效,但我想有一个干净的解决方法。
现在我正在这样做,但我必须为创建和更新都这样做,我觉得它很脏:
const patient = new Patient({
_id: new mongoose.Types.ObjectId(),
lastName: req.body.lastName,
firstName: req.body.firstName,
phone: req.body.phone,
mobile: req.body.mobile,
email: req.body.email,
subscriptionDate: req.body.subscriptionDate ? req.body.subscriptionDate : undefined,
gender: req.body.gender,
birthDate: req.body.birthDate,
nbChildren: req.body.nbChildren,
job: req.body.job,
address: req.body.address
});
patient.save()
.then(result => {
console.log(result);
res.status(201).json({
message: 'Handling POST requests to /patients',
createdPatient: patient
});
})
.catch(err => {
console.log(err);
const error = new Error(err);
next(error);
});
解决方案
Mongoose 默认值仅在您的文档对象键未定义这些字段时才有效。[empty,null]
是有效值。正如您在创建对象时处理的那样,这是我可以在这里看到的一种方式,即您可以分配undefined
,或者您可以从对象中删除该属性。
推荐阅读
- c# - Unity WebGL 禁用 cookie 或如何从 url 更新游戏对象
- android - android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri) 抛出内存不足异常
- mysql - MySQL版本的混乱
- sql-server - 为什么我在 SQL Developer 工具的 SQL Server 表中看到重复出现的列?
- python - 使用嵌套 if 语句的具有多个条件的 Python While 循环
- font-awesome - 如何将 Font Awesome 与 Polymer LitElement 一起使用
- mysql - Hive 创建表失败
- c++ - while 循环中的 ofstream outputfile() 通常会生成空文件
- git - 查找(部分)文件何时在 git 中移动
- java - Java 代码没有 println 就无法工作