작성한 질문수
[리뉴얼] React로 NodeBird SNS 만들기
작성
·
358
0
안녕하세요 선생님.
콘솔에 post.addHashTags is not a function이라고 뜨면서 막상 데이터베이스에는 등록이 된 경우는 왜 그런 건가요?
테이블을 확인해보면 posts와 hashtags 테이블 둘 다 데이터가 잘 들어와있습니다.
답변 1
일단 post 모델 보여주셔야 할 것 같고, 게시글 등록 라우터도 보여주셔야 합니다.
제가 강의 보고 따라 만들다가 제가 놓친 부분이 있었는지...저는 처음 모델 설계를
module.exports = (sequelize, DataTypes) => { const Post = sequelize.define('Post', { content: { type: DataTypes.TEXT, allowNull: false }, lookName: { type: DataTypes.STRING(30), allowNull: false }, top: { type: DataTypes.STRING(30), allowNull: true }, bottom: { type: DataTypes.STRING(30), allowNull: true }, dress: { type: DataTypes.STRING(30), allowNull: true }, shoes: { type: DataTypes.STRING(30), allowNull: true }, acc: { type: DataTypes.STRING(30), allowNull: true }, }, { charset: 'utf8mb4', collate: 'utf8mb4_general_ci', }); Post.associate = (db) => { db.Post.belongsTo(db.User); db.Post.belongsToMany(db.Hashtag, {through: 'PostHashtag'}); db.Post.hasMany(db.Comment); db.Post.hasOne(db.Image); db.Post.belongsToMany(db.User, {through: 'Like', as:'Likers'} ); db.Post.belongsTo(db.Post, {as: 'Reference '}); }; return Post; }
이렇게 했다가 선생님 깃헙 보니까 모델들이
const DataTypes = require('sequelize'); const { Model } = DataTypes; module.exports = class Post extends Model{ static init(sequelize){ return super.init({ content: { type: DataTypes.TEXT, allowNull: false }, lookName: { type: DataTypes.STRING(30), allowNull: false }, top: { type: DataTypes.STRING(30), allowNull: true }, bottom: { type: DataTypes.STRING(30), allowNull: true }, dress: { type: DataTypes.STRING(30), allowNull: true }, shoes: { type: DataTypes.STRING(30), allowNull: true }, acc: { type: DataTypes.STRING(30), allowNull: true }, }, { charset: 'utf8mb4', collate: 'utf8mb4_general_ci', sequelize }) } static associate(db) { db.Post.belongsTo(db.User); db.Post.belongsToMany(db.Hashtag, {through: 'PostHashtag'}); db.Post.hasMany(db.Comment); db.Post.hasOne(db.Image); db.Post.belongsToMany(db.User, {through: 'Like', as:'Likers'} ); db.Post.belongsTo(db.Post, {as: 'Reference '}); }; }
이런 형식으로 설계되어있길래 제가 잘못한줄 알고 두번째 구조로 바꿨거든요. 근데도 앞서 말씀드린 에러 현상은 동일하네요....아무튼 post모델은 이렇고,
const DataTypes = require('sequelize'); const { Model } = DataTypes; module.exports = class Hashtag extends Model { static init(sequelize) { return super.init({ name: { type: DataTypes.STRING(20), allowNull: false, }, }, { modelName: 'Hashtag', tableName: 'hashtags', charset: 'utf8mb4', collate: 'utf8mb4_general_ci', // 이모티콘 저장 sequelize, }); } static associate(db) { db.Hashtag.belongsToMany(db.Post, { through: 'PostHashtag' }); } };
hashTag 모델은 이렇습니다.
코드가 실행되는 부분은
router.post('/', isLoggedIn, upload.none(), async(req, res, next) => { try{ const hashtags = [ req.body.top, req.body.bottom, req.body.dress, req.body.outer, req.body.shoes, req.body.acc ]; const post = await Post.create({ content: req.body.content, lookName: req.body.lookName, top: req.body.top, bottom: req.body.bottom, dress: req.body.dress, outer: req.body.outer, shoes: req.body.shoes, acc: req.body.acc }); if(hashtags){ const result = await Promise.all(hashtags.map((tag) => Hashtag.findOrCreate({ where: {name: tag.slice(1).toLowerCase()} }))); await post.addHashTags(result.map((v) => v[0])); } res.status(201).json(post); } catch(error){ console.error(error); next(error); } });
이러한데, 임의로 hashtags에 배열을 만들어서 때려박긴 했는데 후에 if문으로 데이터 들어온 부분만 배열에 추가되게 바꿀 예정이라, 일단 브라우저에서 데이터를 입력했을 때 해시태그가 생성되는지 먼저 확인해보고 싶어서 저렇게 만들었습니다. 조언 부탁드립니다 선생님ㅠㅠ
대소문자를 주의하세요. post.addHashtags입니다. t가 소문자에요.
아이고..............ㅠㅠㅠㅠㅠㅠㅠㅠ답변 감사합니다 아........
제가 강의 보고 따라 만들다가 제가 놓친 부분이 있었는지...저는 처음 모델 설계를
이렇게 했다가 선생님 깃헙 보니까 모델들이
이런 형식으로 설계되어있길래 제가 잘못한줄 알고 두번째 구조로 바꿨거든요. 근데도 앞서 말씀드린 에러 현상은 동일하네요....아무튼 post모델은 이렇고,
hashTag 모델은 이렇습니다.
코드가 실행되는 부분은
이러한데, 임의로 hashtags에 배열을 만들어서 때려박긴 했는데 후에 if문으로 데이터 들어온 부분만 배열에 추가되게 바꿀 예정이라, 일단 브라우저에서 데이터를 입력했을 때 해시태그가 생성되는지 먼저 확인해보고 싶어서 저렇게 만들었습니다. 조언 부탁드립니다 선생님ㅠㅠ