属性为空时如何触发猫鼬默认值
How to trigger mongoose default value when attribute is null
在我的模式中,我为属性定义了一个默认值:
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
或者您可以从对象中删除 属性。
在我的模式中,我为属性定义了一个默认值:
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
或者您可以从对象中删除 属性。