【发布时间】:2021-04-13 12:09:34
【问题描述】:
我想从 Mongo Schema 访问嵌套元素。我想要做的是当用户喜欢用户 id 的评论时,如果我制作 commentLikes,应该将用户 ID 的评论推送到 commentLikes 数组中,该数组是 cmets 的子元素 作为一个单独的父母,每个评论都有相同的点赞数,例如如果用户 A 喜欢评论 1,他的 id 也会被推送到评论 2。
我的架构是:
const mongoose = require("mongoose")
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
subject: {
type: String,
required: true
},
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
photo: {
type: String,
default: "https://res.cloudinary.com/bigbrain/image/upload/v1616608676/noQ_hvukdh.png"
},
likes: [{
type: ObjectId,
ref: "User"
}],
comments: [{
text: String,
postedBy: {
type: ObjectId,
ref: "User"
},
commentLikes:[{
type: ObjectId,
ref: "User"
}],
}],
postedBy: {
type: ObjectId,
ref: "User"
},
postDate:{
type:String
}
},{timestamps:true})
mongoose.model("Post", postSchema)
我的后端代码:
router.put("/likecomment/:id/:comment_id",requireLogin,(req,res)=>{
const comment = { _id: req.params.comment_id };
Post.findByIdAndUpdate(req.body.postId,{
$push:{comments:req.user._id
}
},{
new:true
}).exec((err,result)=>{
if(err){
return res.status(422).json({error:err})
}
else{
console.log(result)
res.json(result)
}
})
})
我的前端代码是:
const likeComment = (commentid) => {
fetch(`/likecomment/${postid}/${commentid}`, {
method: "put",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("jwt")
},
body: JSON.stringify({
postId: commentid
})
}).then(res => res.json())
.then(result => {
const newData = data.map(item => {
if (item._id === result._id) {
console.log(result)
return result
}
else {
console.log(item)
return item
}
})
setData(newData)
}).catch(err => {
console.log(err)
})
}
我只是想访问后端 cmets 中的 commentLikes,我知道我的逻辑是正确的
Post.findByIdAndUpdate(req.body.postId,{
$push:{comments:req.user._id
}
我也尝试通过 cmets[commentLikes] 访问 commentLikes,但它给了我一个错误。
【问题讨论】:
标签: javascript node.js mongodb express