해시태그 등록 백 부분 질문 입니다.
364
작성한 질문수 23
안녕하세요 선생님.
콘솔에 post.addHashTags is not a function이라고 뜨면서 막상 데이터베이스에는 등록이 된 경우는 왜 그런 건가요?
테이블을 확인해보면 posts와 hashtags 테이블 둘 다 데이터가 잘 들어와있습니다.
답변 1
0
일단 post 모델 보여주셔야 할 것 같고, 게시글 등록 라우터도 보여주셔야 합니다.
0
제가 강의 보고 따라 만들다가 제가 놓친 부분이 있었는지...저는 처음 모델 설계를
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문으로 데이터 들어온 부분만 배열에 추가되게 바꿀 예정이라, 일단 브라우저에서 데이터를 입력했을 때 해시태그가 생성되는지 먼저 확인해보고 싶어서 저렇게 만들었습니다. 조언 부탁드립니다 선생님ㅠㅠ
넥스트 버젼 질문
0
79
2
로그인시 401 Unauthorized 오류가 뜹니다
0
91
1
무한 스크롤 중 스크롤 튐 현상
0
178
1
특정 페이지 접근을 막고 싶을 때
0
105
2
createGlobalStyle의 위치와 영향범위
0
97
2
인라인 스타일 리렌더링 관련
0
93
2
vsc 에서 npm init 설치시 오류
0
150
2
nextjs 15버전 사용 가능할까요?
0
160
1
화면 새로고침 문의
0
124
1
RTK에서 draft, state 차이가 있나요?
0
156
2
Next 14 사용해도 될까요?
0
454
1
next, node 버전 / 폴더 구조 질문 드립니다.
0
350
1
url 오류 질문있습니다
0
212
1
ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out
0
382
1
sudo certbot --nginx 에러
0
1282
2
Minified React error 콘솔에러 (hydrate)
0
472
1
카카오 공유했을 때 이전에 작성했던 글이 나오는 버그
0
249
1
프론트서버 배포 후 EADDRINUSE에러 발생
0
330
1
npm run build 에러
0
519
1
front 서버 npm run build 중에 발생한 에러들
0
384
1
서버 실행하고 브라우저로 들어갔을때 404에러
0
339
2
css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.
0
289
1
팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.
0
243
2
해시태그 검색에서 throttle에 관해 질문있습니다.
0
203
1





