My inventory consists of various products like smartphones, laptops, headphones, etc. However, in the end, all these products are represented as a single generalized ProductsModel
ProductsModel
import { Schema, model } from 'mongoose'
export const productsDiscriminatorKey = 'productKind'
const ProductsSchema = new Schema(
{
name: { type: String },
},
{ productsDiscriminatorKey, timestamps: true }
)
export default model('Products', ProductsSchema)
PhoneModel
import mongoose, { Schema } from 'mongoose'
import ProductsModel, { productsDiscriminatorKey } from './ProductsModel.js'
const PhoneSchema = new Schema(
{
name: { type: String, required: true },
price: { type: String, required: true },
color: { type: String, required: true },
memory: { type: String, required: true },
screen: { type: String, required: true },
fps: { type: String, required: true },
sim: { type: String, required: true },
preview: { type: String, required: true },
images: [{ type: String, required: true }],
category: {
type: mongoose.Schema.ObjectId,
ref: 'Category',
},
type: {
type: mongoose.Schema.ObjectId,
ref: 'Type',
},
count: { type: Number },
},
{ productsDiscriminatorKey }
)
const PhoneModel = ProductsModel.discriminator('Phones', PhoneSchema)
export default PhoneModel
I have implemented a method for removing products from the database based on quantity rather than deleting the entire model at once. The logic works correctly when used in specific models like PhoneModel
, but not when tried from ProductsModel
. The count
field remains unchanged.
Delete logic
async delete(req, res) {
try {
const { id } = req.params
const { count } = req.body
const candidate = await ProductsModel.findById(id)
if (candidate.count < count) {
return res.status(500).json({ message: 'More than count in base' })
}
if (candidate.count === count || !count) {
await ProductsModel.findByIdAndDelete(id)
return res.status(200).json({ message: 'All deleted' })
}
if (candidate.count > count) {
await ProductsModel.findByIdAndUpdate({ _id: id }, { count: candidate.count - count })
return res.status(200).json({ message: `${count} successfully deleted` })
}
} catch (error) {
return res.status(500).json({ message: 'Server error' })
}
}
In certain scenarios, only a specific quantity (count
) needs to be deleted and not all at once. This is achieved by adjusting the count field using findByIdAndUpdate
. Despite implementing this logic, it does not function as expected without any error messages.