exports.createBudget = async (req, res) => {
/*
Structure of revenueCategories Array from req.body
[{
"categoryName":"Salary",
"categoryAmount":"35000",
"type":"revenue",
"categoryValue":"salary",
"added":true
}, {
"categoryName":"Other Source",
"categoryAmount":"2000",
"type":"revenue",
"categoryValue":"other-source",
"added":true
}]
*/
const revenueData = await req.body.revenueCategories.map(async (el) => {
//Check if Revenue exists in Revenue Model's Collection, if true get it's _id
let currentDoc = await Revenue.findOne({
categoryValue: el.categoryValue,
}).select('_id');
//if we have _id then assign it to categoryId property
if (currentDoc !== null) {
el.categoryId = await currentDoc._id;
}
//if new Revenue Category then create new Doc and assign it's _id to categoryId property
else if (currentDoc === null) {
let newCategData = {
categoryName: el.categoryName,
categoryValue: el.categoryValue,
};
let newCateg = await Revenue.create(newCategData);
el.categoryId = await newCateg._id;
}
console.log(el); //show el object with correct categoryId
return el;
});
console.log('Revenue Data', revenueData); //***this gives array of pending promises***
const budgetDoc = {
...req.body.budgetData,
revenueData, //first testing with revenue, then will do the same with expense below
expenseData: req.body.expenseCategories,
};
const budget = await Budget.create(budgetDoc);
res.status(201).json({
data: {
status: 'success',
budget,
},
});
};