我的模型> user.js 文件中出现以下错误。 将商品添加到购物车时。
当我评论价格并使其消失时,错误消失了,但在Compass中再也看不到现场价格。
我收到错误:(节点:6659)UnhandledPromiseRejectionWarning:ValidationError:
用户验证失败:cart.items.0.price:路径price
是必需的。
我的模型>> product.js 上产品模式的代码为:
const productSchema = new Schema({ //set up blue print of products
title: {
type: String,
required: true
},
category: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
imageUrl: {
type: String,
required: true
},
//products should be linked to users schema
userId: {
type: Schema.Types.ObjectId,
ref:'User',
required: true
}
});
这是我的模型>> user.js
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
cart: {
items: [{
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true },
quantity: {
type: Number,
required: true },
price: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true },
}]
}
});
userSchema.methods.addToCart = function (product) {
const cartProductIndex = this.cart.items.findIndex(cp => {
return cp.productId.toString() === product._id.toString();
});
let newQuantity = 1;
const updatedCartItems = [...this.cart.items];
if (cartProductIndex >= 0) {
newQuantity = this.cart.items[cartProductIndex].quantity + 1;
updatedCartItems[cartProductIndex].quantity = newQuantity;
} else {
updatedCartItems.push({
productId: product._id,
quantity: newQuantity,
price: product.price,
// priceTotal: newPriceTotal
});
}
const updatedCart = {
items: updatedCartItems
};
this.cart = updatedCart;
return this.save();
};
如何在不影响其余价格的情况下增加价格?