在我的模式中,我为属性定义了默认值:
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}
});
我希望在传递的值为null时使用它。我知道它只有在未定义的情况下才有效,但是我想这有一个干净的解决方法。
现在我正在执行此操作,但是我必须同时进行创建和更新,并且感觉很脏:
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);
});
答案 0 :(得分:0)
猫鼬默认值仅在未定义文档对象键的情况下有效。 [empty,null]
是有效值。在创建对象时,这就是我在这里看到的一种方法,即可以分配undefined
或从对象中删除该属性。