У меня есть две модели, названные Product и User.
Продукт имеет список пользователей, которые добавили продукт в корзину.
У пользователей есть объект корзины с 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});
Я хочу, чтобы при удалении товара он удалялся из корзины пользователей, а итоговая сумма корзины вычиталась из цены * количества товара в этой корзине.