Error Handling/에러핸들링

EagerLoadingError [SequelizeEagerLoadingError]: PostLikes is not associated to Posts!

sangwoo_rhie 2023. 7. 6. 16:37

 

// 2. 게시글 목록조회  GET : localhost:3018/api/posts (성공)
router.get('/posts', async (req, res) => {
    const postList = await Posts.findAll({
    attributes: ['postId', 'title', 'createdAt', 'updatedAt'],
    include: [{model: Users, attributes: ["nickname"]}, {model: PostLikes, attributes: ["likedCount"] }],
    order: [['createdAt', 'DESC']], //createdAt을 기준으로 내림차순 정렬
    });
    return res.status(200).json({"게시글 목록": postList}); // data
});

 

위와 같은 코드를 작성하다가 에러가 발생했다. 이유는 Posts모델에서 findAll을 해오는데, attributes로 쓰이는 PostLikes 모델이 연결되어 있지 않았다. 따라서 아래와 같이 연결지었다.

 

 

 

 

 

EagerLoadingError [SequelizeEagerLoadingError]: PostLikes is not associated to Posts!
    at Posts._getIncludedAssociation (C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\node_modules\sequelize\lib\model.js:565:13)
    at Posts._validateIncludedElement (C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\node_modules\sequelize\lib\model.js:502:53)
    at C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\node_modules\sequelize\lib\model.js:421:37
    at Array.map (<anonymous>)
    at Posts._validateIncludedElements (C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\node_modules\sequelize\lib\model.js:417:39)
    at Posts.findAll (C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\node_modules\sequelize\lib\model.js:1124:12)
    at async C:\Users\admin\Desktop\코딩\NODE\4th Week\Sequelize-Relations (Lv.4)\routes\posts.js:33:22

Node.js v18.16.0