I have 2 models for database, user and his post
modelUser.js
const User = sequelize.define('user', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
email: {type: DataTypes.STRING, unique: true},
password: {type: DataTypes.STRING},
});
modelPost.js
const Post = sequelize.define('post', {
author: {type: DataTypes.STRING},
title: {type: DataTypes.STRING},
content: {type: DataTypes.STRING}
});
I create a createPost method, and in order to create a new element in the 'post' table, I need to get the user's email from the 'user' table, and then assign the email value to the 'author' field
async createPost(req,res) {
try {
const {author} = await User.findOne({where: {email}}); //this does not work
console.log(author);
const {title, content} = req.body;
/*if(!title || !content) {
return res.status(400).json({message: 'Title or content cannot be empty'});
}
const post = await Post.create({author, title, content})*/
return res.json({post});
} catch (e) {
console.log(e.message);
}
}
So, how do I access the user table and get the email of a specific user? To check if the user is registered use authMiddleware
router.post('/registration', userController.registration);
router.post('/login', userController.login);
router.get('/get', authMiddleware, userController.findAll);
router.post('/getOne',authMiddleware, userController.findOne);
router.post('/post', authMiddleware, userController.createPost);