I have several types of products such as phones, laptops, headphones, etc. All of these products in the end result turns out to be you one 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 implemented the logic of removing products from the database by quantity, rather than the entire model at once. If I use it specifically in the PhoneModel
or in another model (not in the ProductsModel
), then all the logic works correctly. But as soon as I try to do this from ProductsModel
, then it just doesn’t change the count
field.
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' })
}
}
That is, there is a case when you need to delete not all at once, but a certain amount (count
). I implemented this by simply changing the count field using findByIdAndUpdate
. But it just doesn’t work out and doesn’t throw out any errors.