我正在创建一个猫鼬条目,这是我的模式:
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"
创建订单时,我需要从对象创建中删除此键和值。
如果优惠券代码为空,如何删除此密钥?
预先感谢
答案 0 :(得分:0)
问题是您试图在数据类型的objectID中填充空字符串值。
对此的一种可能的解决方案是在代码中使用以下条件:
coupon: body.coupon.code ? body.coupon.code : null
如果body.coupon.code为“”,这会将优惠券设置为null。