| Current Path : /proc/thread-self/root/home/deltalab/PMS/partner-manager-backend/services/ |
| Current File : //proc/thread-self/root/home/deltalab/PMS/partner-manager-backend/services/category.js |
const { categoryModel } = require ('../models/mongoose/category');
const jsonTaxonomy = require('./utils/taxonomy.json');
async function saveSubcategories(categories, parentId) {
for (const [key, subcategory] of Object.entries(categories)) {
const category = new categoryModel();
if (key !== 'id') {
category.googleId = subcategory.id ? subcategory.id : null;
category.name = [{ code: 'it-IT', label: key }];
category.parentId = parentId ? parentId : null;
category.isRoot = parentId ? false : true;
category.isLeaf = true;
// check if the category already exists in the db
const existingCategory = await categoryModel.findOne({ googleId: category.googleId });
if (existingCategory) {
return true;
}
// save category
const savedCategory = await category.save();
if (parentId) {
// find parent and update its children
const updatedCategory = await categoryModel.findOneAndUpdate(
{ _id: savedCategory.parentId },
{ $push: { childrenId: savedCategory._id } }
);
}
await saveSubcategories(subcategory, category._id);
}
}
return false;
}
async function initCategoriesDb() {
const exist = await saveSubcategories(jsonTaxonomy, null);
// set leaf categories
if (!exist) {
await categoryModel.updateMany(
{ childrenId: { $exists: true, $not: { $size: 0 } } },
{ isLeaf: false },
);
}
}
module.exports = {
initCategoriesDb,
};