This is a node db problem. I include the user model but it is not included in the result

51 views Asked by At

What's wrong with the api or router? I definitely included the user model Why is no user information included? Below is the api logic for loading an existing post.

Since the author information is also required, the user model information is included using the include syntax below.

User information is not printed. What is the reason?

git https://github.com/hyunsokstar/node_bird_22

api code

router.get('/', async (req, res, next) => { // GET /api/posts
    try {
        const posts = await db.Post.findAll({
            include: [{
                model: db.User,
                attributes: ['id', 'nickname'],
            }],
            order: [['createdAt', 'DESC']], // DESC는 내림차순, ASC는 오름차순
        });
        console.log("posts : ", posts);

        res.json(posts);
    } catch (e) {
        console.error(e);
        next(e);
    }
});

model

// back\models\post.js

module.exports = (sequelize, DataTypes) => {
    const Post = sequelize.define('Post', { // 테이블명은 posts
        content: {
            type: DataTypes.TEXT, // 매우 긴 글
            allowNull: false,
        },
    }, {
        charset: 'utf8mb4', //  한글+이모티콘
        collate: 'utf8mb4_general_ci',
    });

    Post.associate = (db) => {
        db.Post.belongsTo(db.User); // 테이블에 UserId 컬럼이 생겨요
        db.Post.hasMany(db.Comment);
        db.Post.hasMany(db.Image);

        // 릴레이션 관계 추가
        db.Post.belongsTo(db.Post, { as: 'Retweet' }); // RetweetId 컬럼 생성
        db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag' });
        db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' });
    };

    return Post;

};

result

  Post {
    dataValues:
     { id: 21,
       content: 'write test',
       createdAt: 2019-11-07T09:43:00.000Z,
       updatedAt: 2019-11-07T09:43:00.000Z,
       UserId: 1,
       RetweetId: null,
       User: [User] },
    _previousDataValues:
     { id: 21,
       content: 'write test',
       createdAt: 2019-11-07T09:43:00.000Z,
       updatedAt: 2019-11-07T09:43:00.000Z,
       UserId: 1,
       RetweetId: null,
       User: [User] },
    _changed: {},
    _modelOptions:
     { timestamps: true,
       validate: {},
       freezeTableName: false,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       charset: 'utf8mb4',
       collate: 'utf8mb4_general_ci',
       sequelize: [Sequelize],
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       include: [Array],
       includeNames: [Array],
       includeMap: [Object],
       includeValidated: true,
       attributes: [Array],
       raw: true },
    isNewRecord: false,
    User:
     User {
       dataValues: [Object],
       _previousDataValues: [Object],
       _changed: {},
       _modelOptions: [Object],
       _options: [Object],
       isNewRecord: false } } ]
1

There are 1 answers

1
Jahanzaib On BEST ANSWER
const where = {};
let options = { where };

options.include = [
    {
        model: db.User,
        attributes: ['id', 'nickname'],
    },
];
options.order = [['createdAt', 'DESC']];

const posts = await db.Post.findAll(options);

Try this it will help