我有两个分别名为“产品”和“用户”的模型。 产品具有已在购物车中添加产品的用户列表。 用户有一个带有cartTotal的购物车对象,以及一个带有productId,数量和totalAmount(即Product.price *数量的总和)的对象
删除产品时,应从拥有该产品的用户的购物车中删除该产品。
我一直在尝试填充方法,但是失败了。
产品型号如下:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
imageUrl: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
cartOfUsers: [
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
}, {timestamps: true});
module.exports = mongoose.model('Product', productSchema);
用户模型如下:
// default packages import
// third party imports
const mongoose = require('mongoose');
// own imports
const Product = require('./product');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
products: [
{
type: Schema.Types.ObjectId,
ref: 'Product'
}
],
cart: {
items: [
{
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
},
itemTotal: {
type: Number,
required: true
}
}
],
cartTotal: {
type: Number,
required: true
}
},
verifyToken: {
type: String,
required: true
},
verified: {
type: Boolean,
required: true
},
resetToken: String,
resetTokenExpiration: Date
}, {timestamps: true});
我希望在删除产品时,从用户的购物车中删除该产品,然后将购物车Total乘以该购物车中该产品的价格*数量。