I recently imported my Database from Sql Server to MongoDB, converting to a full MERN stack. I have a titles_table, a skills_table, and a title_skills_table. The title_skills_table is a 'join' table that holds the _ids of the skills and title tables as some skills can fall under multiple titles.
I'm trying to call all title_skills associated with a particular title, which I've been able to do. What I can't figure out is how to use that title_skills array response to find all the skills by skill_id in the skills_table.
I've tried async waterfall, async chaining, among other things, but it's either just returning an empty error message or breaking the server.
I can do the two calls individually and get a response from each, it's joining them in a looping chain that seems to kill me.
Here's what I currently have:
const router = require('express').Router();
const Skill = require('../models/Skill');
const TitleSkills = require('../models/TitleSkills');
//Get A Skill by Skill Id
router.get("/skill/:id", async (req, res) => {
try {
const skill = await Skill.findOne({skill_id: req.params.id}).populate('SkillCategory')
res.json(skill);
} catch (err) {
res.json({ message: err });
}
});
//Get TitleSkills by TitleId *by itself
// router.get("/title/:id", async (req, res) => {
// try {
// const titleSkills = await TitleSkills.find({title_id: req.params.id})
// res.json(titleSkills)
// } catch (err) {
// res.json({ message: err });
// }
// });
//Get a skill by skill id and through it in an array
const getSkillsByskillId = (id) => new Promise((resolve, reject) => {
const skillsArr = []
router.get(`/skill/${id}`)
.then((result) => resolve(skillsArr.push(result.data)))
return(skillsArr)
.catch(error => reject(error))
});
//Get all TitleSkills by TitleId and loop each TitleSkill through Skills Table
router.get("/title/:id", async (req, res) => {
try {
const titleSkills = await TitleSkills.find({title_id: req.params.id})
.then(titleSkills.forEach((ts) => {
getSkillsByskillId(ts.skill_id)
}))
res.json(titleSkills)
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
#saveme