简体   繁体   English

如果值为空则忽略键

[英]Ignore key if empty value

I'm creating a mongoose entry, and this is my schema:我正在创建一个 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,
    },
});

Coupon is optional.优惠券是可选的。 The code to create a new order is:创建新订单的代码是:

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

However, when coupon is an empty string I get a MongooseError [CastError]: Cast to ObjectID failed for value "" at path "coupon"但是,当优惠券是空字符串时,我得到一个MongooseError [CastError]: Cast to ObjectID failed for value "" at path "coupon"

I need to remove this key and value from the object creation, when creating the order.创建订单时,我需要从 object 创建中删除此键和值。

How can I remove this key if coupon code is empty?如果优惠券代码为空,如何删除此密钥?

Thanks in advance提前致谢

The issue is you are trying to fit an empty string value in the data-type objectID.问题是您试图在数据类型 objectID 中填充一个空字符串值。

A possible solution to this is to use below condition in your code:一个可能的解决方案是在您的代码中使用以下条件:

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

This will set coupon to null in case body.coupon.code is "".如果 body.coupon.code 为“”,这会将优惠券设置为 null。

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

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