Sequelize include is not working with hasOne relationship

Hi i have a User model and a ProfilePicture model. The user can only have 1 profile picture and a profile picture can only belong to one user.

My problem is in my get request i am calling the profile picture model and including the users model, i get just my profile picture without my user object.

User.hasOne(pp,
    { foreignKey: "userId" }
);

pp.belongsTo(User,
    { foreignKey: "userId" }
);

router.get(
    "/pp",
    auth,
    async (req, res) => {
        let { id } = req.user;

        await pp.findOne({
            where: {
                userId: id
            }
        },
        {
            include: [{
                model: User,
            }]
        }).then((user) => {
            console.log(user)
                
            if (!user)
                return res.status(404).send();

            res.send(user);
        });
    });

Answer

You need to include include in the first parameter.

await pp.findOne({
  where: {
    userId: id
  },
  include: [
    {
      model: User
    }
  ]
});

Leave a Reply

Your email address will not be published. Required fields are marked *