【发布时间】:2021-11-03 21:00:27
【问题描述】:
我正在构建一个简单的社交平台;我目前正在构建评论帖子的模式,但用户也应该能够评论其他 cmets。所以我想要做的是,一旦用户在帖子上遇到问题,就会检查 postId 参数是否与数据库中的 post._id 匹配的条件,因此这是一个更高阶的评论操作。现在,如果我要评论其他人的评论,我会检查 post._id 是否与帖子匹配,以及检查 comment._id 是否也匹配,但是将其插入嵌套数组时会出现问题。
架构(POST)
onst mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema({
uid: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "users",
},
uname: {type: String, required: true},
upic: {type: String, required: true},
message: { type: String,},
media: {type: String,},
likes:[],
comments:[],
commentCount: {type: Number, default: 0},
likeCount: {type: Number, default: 0},
repostCount: {type: Number, default: 0},
postedOn: { type: Date},
});
postSchema.pre('save', function(next){
this.postedOn = Date.now();
next();
});
var PostModel = mongoose.model('posts', postSchema);
module.exports = PostModel;
控制器(评论)
{/* Higher order comment */}
module.exports.commentPost = async (req, res) => {
try{
await PostModel.findByIdAndUpdate(req.params.postId,
{
$push: {
comments: [{
_id: uuid.v1(),
postId: req.params.postId,
uid: req.user._id,
message: req.body.message,
postedOn: Date.now(),
uname: req.user.name,
upic: req.user.pic,
likes: [],
comments: [],
likeCount: 0,
commentCount: 0,
}]
},
$inc: { commentCount: 1}
}).exec((err,result)=>{
if(err){
return res.status(422).json({error:err})
}else{
res.json(result)
}
});
} catch(err){
throw new ErrorResponse(err, 404);
}
}
{/* Lower order comment */}
module.exports.commentCommentPost = async (req, res) => {
try{
await PostModel.findByIdAndUpdate({"_id": req.params.postId, "comments._id": req.body.commentId},
{
$push: {
comments: [{
comments: [{
_id: uuid.v1(),
postId: req.params.postId,
uid: req.user._id,
message: req.body.message,
postedOn: Date.now(),
uname: req.user.name,
upic: req.user.pic,
likes: [],
comments: [],
likeCount: 0,
commentCount: 0,
}]
}]
},
$inc: { commentCount: 1}
}).exec((err,result)=>{
if(err){
return res.status(422).json({error:err})
}else{
res.json(result)
}
});
} catch(err){
throw new ErrorResponse(err, 404);
}
}
我必须通过更新嵌套数组中的嵌套数组做错了,任何帮助将不胜感激。
【问题讨论】: