diff --git a/src/controllers/admin-controllers/createCategory.js b/src/controllers/admin-controllers/createCategory.js index 9e66e89d..ed93fc9c 100644 --- a/src/controllers/admin-controllers/createCategory.js +++ b/src/controllers/admin-controllers/createCategory.js @@ -3,11 +3,15 @@ import SettingsModel from "../../models/Settings.js"; export default async function createCategory(category, session) { try { const respond = await SettingsModel.updateOne( - {}, - { $push: { productsCategories: [category] } }, + { productsCategories: { $nin: [category] } }, + { $addToSet: { productsCategories: [category] } }, { session } ); - return !!respond.modifiedCount; + + if (respond.acknowledged && respond.modifiedCount === 0) { + return null + } + return !!respond.modifiedCount } catch (error) { console.log(error) return; diff --git a/src/routes/admin_routes/products_createCategory_post.js b/src/routes/admin_routes/products_createCategory_post.js index 77b16e18..e6347899 100644 --- a/src/routes/admin_routes/products_createCategory_post.js +++ b/src/routes/admin_routes/products_createCategory_post.js @@ -11,6 +11,9 @@ export default asyncRouteHandler( const session = await startSession(); session.startTransaction(); const dbUpdateResponse = await AdminController.createCategory(category, session); + if (dbUpdateResponse === null) { + return next(new ErrorGenerator("The category already exist", 400)); + } const cacheUpdateResponse = await updateRedisCache("store-variables", (variablesObject) => { variablesObject?.productsCategories.push(category) return variablesObject @@ -23,7 +26,7 @@ export default asyncRouteHandler( res.status(400).json(false); } } else { - next(new ErrorGenerator("You didn't provide a valid category name", 400)) + next(new ErrorGenerator("Ivalid Category Name", 400)); } } ) \ No newline at end of file