首页 > 解决方案 > 属性为空时如何触发猫鼬默认值

问题描述

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

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

标签: mongoosemongoose-schema

解决方案


Mongoose 默认值仅在您的文档对象键未定义这些字段时才有效。[empty,null]是有效值。正如您在创建对象时处理的那样,这是我可以在这里看到的一种方式,即您可以分配undefined,或者您可以从对象中删除该属性。


推荐阅读