Skip to content

Commit a07946f

Browse files
committed
fix updatepost function
1 parent 6290854 commit a07946f

1 file changed

Lines changed: 19 additions & 13 deletions

File tree

controllers/postController.js

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ exports.createPost = async (req, res) => {
9393

9494
exports.updatePost = async (req, res) => {
9595
try {
96-
// 👇 1. 加入 coverImage 和 createdAt
96+
console.log('--- UPDATE REQUEST RECEIVED ---');
97+
console.log('Target createdAt:', req.body.createdAt);
98+
9799
const { title, content, excerpt, status, categoryId, tagIds, coverImage, createdAt } = req.body;
98100
const post = await Post.findByPk(req.params.id);
99101

@@ -105,30 +107,33 @@ exports.updatePost = async (req, res) => {
105107
return res.status(403).json({ message: '没有权限修改此文章' });
106108
}
107109

108-
// 👇 2. 构建更新对象
109-
const updateData = {
110-
title,
111-
content,
112-
excerpt,
113-
status,
114-
categoryId: categoryId || post.categoryId,
115-
coverImage: coverImage // 保存封面
116-
};
110+
// 设置常规字段 改用直接赋值,比构建 updateData 对象更直观
111+
post.title = title;
112+
post.content = content;
113+
post.excerpt = excerpt;
114+
post.status = status;
115+
post.categoryId = categoryId || post.categoryId;
116+
post.coverImage = coverImage;
117117

118-
// 👇 3. 上帝模式:只有当用户真的传了时间才更新它,否则保持原样
118+
// 暴力强制更新时间
119+
// 普通的 update() 会被 Sequelize 过滤,必须用 setDataValue 绕过保护
119120
if (createdAt) {
120-
updateData.createdAt = createdAt;
121+
post.setDataValue('createdAt', createdAt);
122+
console.log('>>> FORCE UPDATING createdAt to:', createdAt);
121123
}
122124

123-
await post.update(updateData);
125+
// 执行保存
126+
await post.save();
124127

128+
// 处理标签
125129
if (tagIds) {
126130
await post.setTags([]);
127131
if (tagIds.length > 0) {
128132
await post.addTags(tagIds);
129133
}
130134
}
131135

136+
// 返回结果
132137
const updatedPost = await Post.findByPk(post.id, {
133138
include: [
134139
{ model: User, as: 'author', attributes: ['id', 'username'] },
@@ -139,6 +144,7 @@ exports.updatePost = async (req, res) => {
139144

140145
res.json({ message: '文章更新成功', post: updatedPost });
141146
} catch (error) {
147+
console.error('Update Error:', error); // 建议加上错误日志
142148
res.status(500).json({ message: '服务器错误', error: error.message });
143149
}
144150
};

0 commit comments

Comments
 (0)