How to get data from one table and use it in another in sequelize(postgres)

Viewed 27

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);
2 Answers

Hello @andreySmith, the destructuring you're doing is not correct (check the below lines).

const {author} = await User.findOne({where: {email}}); //You need to update this line as below in createPost().

const {email} = await User.findOne({where: {email}});

As you written before the trouble lies at this line

const {author} = await User.findOne({where: {email}});

And the solution is pretty simple.
When you're trying to destructure you either have to use the same name as the object has i.e. in this case it's email

 const { email } = await User.findOne({where: {email}});

or use naming destructuring so your line should be transformed into something like this:

 const { email : author } = await User.findOne({where: {email}});

Now you can use author variable that contains value from email.

Related