I have a table called Stories there are few columns and 3 foreign keys: category, sub category and language.
To make association, I have added sequelize function as below which added CategoryId, SubCategoryId and LanguageId columns to the Story table.
story.belongsTo(category, { as: 'Category' });
story.belongsTo(subCategory, { as: 'SubCategory' });
story.belongsTo(language, { as: 'Language' });
How can I add story to story table? Below is my code.
const Category = require('../models/category');
const SubCategory = require('../models/subCategory');
const Language = require('../models/language');
exports.postStory = (req, res, next) => {
const storyTitle = req.body.title;
const description = req.body.description;
const categoryId = req.body.categoryId;
const subCategoryId = req.body.subCategoryId;
const languageId = req.body.languageId;
Category.findOne({
where: {
id: categoryId
}
}).then(category => {
return SubCategory.findOne({
where: {
id: subCategoryId
}
})
}).then(subcategory => {
return Language.findOne({
where: {
id: languageId
}
}).then(language => {
//save operation here
const story = new Story({
story_type: storyType,
title: storyTitle,
description: description,
categoryId: categoryId,
subCategoryId: subCategoryId,
languageId: languageId,
createdBy: 1
});
return story.save()
.then((result) => {
res
.status(201)
.json({
message: "Story added to database",
statusCode: 201,
CreatedBy: 1,
result: result,
});
})
})
}).catch((error) => {
if (!error.statusCode) {
error.statusCode = 500;
}
next(error);
});
Although it is adding stories to Story table but it is not adding categoryId, Sub categoryId and languageId, it is adding only null values for those fields as per below screen capture.
I cannot figure out how to add CategoryId, SubCategoryId, LanguageId to story.
