属性为空时如何触发mongoose默认值

属性为空时如何触发mongoose默认值,mongoose,mongoose-schema,Mongoose,Mongoose Schema,在我的模式中,我为属性定义了一个默认值: const patientSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, lastName: {type : String, required: true}, firstName: {type : String, required: true}, phone: String, mobile: String, email: Str

在我的模式中,我为属性定义了一个默认值:

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

Mongoose默认值仅在文档对象键未定义这些字段时有效<代码>[空,空]是有效值。当您在对象创建时进行处理时,这是我在这里看到的一种方式,即您可以指定
未定义的
,或者您可以从对象中删除该属性。

只有在您的文档对象键未定义这些字段时,Mongoose默认值才起作用<代码>[空,空]
是有效值。当您在对象创建时处理时,这是我在这里看到的一种方式,即您可以指定
未定义的
,或者您可以从对象中删除该属性。

嗯,好的。我想我会坚持我的肮脏的变通方法。谢谢你,嗯,好的。我想我会坚持我的肮脏的变通方法。非常感谢