인프런 커뮤니티 질문&답변
해쉬태그 검색 응용관련 질문입니다.
작성
·
379
0
안녕하세요 제로초님 강의 잘듣고있습니다.
강의에서 설명해주신 해쉬태그 검색기능을 저는 응용해서 포스트의 컨텐츠내용 전체를 포함해서 검색하는 기능을 구현하고 있습니다.
근데 다음과 같이 router를 구현하니 비어있는 포스트를 반환하더라고요.
그래서 해당 기능을 구현하려면 아래 코드에서 어떤 부분이 문제인지 피드백좀 부탁드리겠습니다.
참고 코드와 post테이블의 구조 함께 첨부하겠습니다.
router.get('/:tag', async (req, res, next) => { // loadHashtagPostsAPI / GET /hashtag/1
try {
const where = {};
if (parseInt(req.query.lastId, 10)) {
where.id = { [Op.lt]: parseInt(req.query.lastId, 10)};
where.title ={ [Op.like]: "%" + decodeURIComponent(req.params.tag) + "%" }; // 추가코드
where.recipes ={ [Op.like]: "%" + decodeURIComponent(req.params.tag) + "%" }; // 추가코드
}
const posts = await Post.findAll({
where,
limit: 10,
order: [['createdAt', 'DESC']],
include: [{
model: Hashtag,
where: { name: decodeURIComponent(req.params.tag) },
}, {
model: User,
attributes: ['id', 'nickname'],
}, {
model: User,
as: 'Likers',
attributes: ['id'],
}, {
model: Comment,
include: [{
model: User,
attributes: ['id', 'nickname'],
}],
}, {
model: Image,
}]
});
res.status(200).json(posts);
} catch (error) {
console.error(error);
next(error);
}
});const DataTypes = require('sequelize');
const { Model } = DataTypes;
module.exports = class Post extends Model {
static init(sequelize) {
return super.init({
title: {
type: DataTypes.TEXT,
allowNull: false,
},
desc: {
type: DataTypes.TEXT,
},
ingredient: {
type: DataTypes.TEXT,
allowNull: false,
},
recipes: {
type: DataTypes.TEXT,
allowNull: false,
},
tips: {
type: DataTypes.TEXT,
},
tags: {
type: DataTypes.TEXT,
},
}, {
modelName: 'Post',
tableName: 'posts',
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.hasMany(db.Image);
db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' });
}
};



