如何在MongoDB中将新创建的帖子添加到用户的createdPosts数组?
问题描述
我正在搭建一个社交平台,用户可以在平台上发布帖子。用户创建帖子后,需要把帖子添加到该用户的createdPosts列表里,请问该怎么更新这个列表?
我尝试的代码
新增帖子的接口代码
export const addPost = async (req, res, next) => { try{ const newPost = new Post({userId : req.user.id, ...req.body}) const savedPost = await newPost.save() console.log(savedPost._id) const updatedUser = await User.findByIdAndUpdate( req.user.id, { $push: { createdPosts: savedPost._id } }, // Push the post ID to the array { new: true } ); res.status(200).json(savedPost) }catch(err){ next(err) } }
User Schema
import mongoose from 'mongoose' const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, createdPosts: { type: Array, default: [] }, likedPosts: { type: Array, default: [] // Using a function as the default value }, bookmarkedPosts: { type: Array, default: [] } }, {timestamps: true}) export default mongoose.model("User", UserSchema);
Post Schema
import mongoose from "mongoose" const PostSchema = new mongoose.Schema({ userId: { type: String, required: true }, title: { type: String, }, body: { type: String, }, tags: { type: [String], default: [] }, likes: { type: Number, default: 0 } }, {timestamps: true}) export default mongoose.model("Post", PostSchema)
解决方案与优化建议
规范Schema数组类型
你当前把createdPosts定义为普通Array,建议改成mongoose的ObjectId数组并关联Post模型,这样能保证数据的关联性和类型正确性:createdPosts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post", default: [] }]对应的
likedPosts和bookmarkedPosts也可以做同样修改,后续查询用户时可以用populate直接获取帖子详情。保证数据一致性:使用事务
如果帖子保存成功但用户更新失败,会导致数据不一致。可以用mongoose的事务来确保两个操作要么都成功,要么都回滚:export const addPost = async (req, res, next) => { const session = await mongoose.startSession(); session.startTransaction(); try{ const newPost = new Post({userId : req.user.id, ...req.body}) const savedPost = await newPost.save({ session }); const updatedUser = await User.findByIdAndUpdate( req.user.id, { $push: { createdPosts: savedPost._id } }, { new: true, session } ); await session.commitTransaction(); res.status(200).json(savedPost) }catch(err){ await session.abortTransaction(); next(err) } finally { session.endSession(); } }补充错误判断
可以在代码里增加对updatedUser的判断,如果用户不存在(比如被删除),返回对应错误信息:if (!updatedUser) { throw new Error("用户不存在,无法更新帖子列表"); }优化Post的userId类型
Post里的userId也建议改成ObjectId类型关联User模型,保证数据类型统一:userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
内容的提问来源于stack exchange,提问作者user21628260
相关产品推荐
相关产品推荐

