繁体   English   中英

如果值为空则忽略键

[英]Ignore key if empty value

我正在创建一个 mongoose 条目,这是我的架构:

const OrdersSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Users",
        required: true,
    },
    currency: {
        type: String,
        required: true,
    },
    country: {
        type: String,
        required: true,
    },
    rate: {
        type: Number,
        required: true,
    },
    amount: {
        type: Number,
        required: true,
    },
    coupon: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Coupons",
    },

    subtotal: {
        type: Number,
        required: true,
    },
    total: {
        type: Number,
        required: true,
    },
    recipient: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
    },
    status: {
        type: String,
        required: true,
        default: "On-hold",
    },
    payment: {
        type: Object,
        required: true,
    },
    shortId: {
        type: String,
        required: true,
    },
    createdAt: {
        type: Date,
        default: Date.now,
        required: true,
    },
});

优惠券是可选的。 创建新订单的代码是:

const order = await Orders.create({
            user: req.id,
            currency: body.selectedCountry,
            country: body.selectedCountry,
            rate: rate.rates[body.selectedCountry],
            amount: body.amount,
            coupon: body.coupon.code,
            subtotal: body.subtotal,
            total: body.total,
            recipient: body.recipient,
            payment: body.paymentData,
            shortId: shortid.generate(),
        });

但是,当优惠券是空字符串时,我得到一个MongooseError [CastError]: Cast to ObjectID failed for value "" at path "coupon"

创建订单时,我需要从 object 创建中删除此键和值。

如果优惠券代码为空,如何删除此密钥?

提前致谢

问题是您试图在数据类型 objectID 中填充一个空字符串值。

一个可能的解决方案是在您的代码中使用以下条件:

coupon: body.coupon.code ? body.coupon.code : null

如果 body.coupon.code 为“”,这会将优惠券设置为 null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM