简体   繁体   English

在 MongDB 中推送嵌套的 Object

[英]Pushing Nested Object in MongDB

I want to access nested element from Mongo Schema.我想从 Mongo Schema 访问嵌套元素。 What I am trying to do is when user likes a comment of a user id should be pushed in the commentLikes array which is a child of comments if I make commentLikes as a seprate parent each comment have same number of likes for example if user A likes comment 1, his id will also be pushed in comment 2.我想要做的是当用户喜欢用户ID的评论时,如果我将commentLikes作为单独的父级,则应该将用户ID的评论推送到commentLikes数组中,该数组是评论的子项评论1,他的id也会被推送到评论2。

My Schema is:我的架构是:

 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)

My Backend Code:我的后端代码:

 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) } }) })

My Front end code is:我的前端代码是:

 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) }) }

I JUST WANTED TO ACCESS THE commentLikes which is inside comments in backend, I know my logic is correct我只是想访问后端评论中的commentLikes,我知道我的逻辑是正确的

 Post.findByIdAndUpdate(req.body.postId,{ $push:{comments:req.user._id }

I also tried accessing commentLikes by comments[commentLikes] but it gives me an error.我也尝试通过comments[commentLikes] 访问commentLikes,但它给了我一个错误。

If I'm understanding right, you're trying to insert the current user's ID into the commentLikes array when the current user likes a comment.如果我理解正确,那么当当前用户喜欢评论时,您会尝试将当前用户的 ID 插入到 commentLikes 数组中。

See Mongo push to array inside array .请参阅Mongo push to array inside array Your current code is going to push a new items into comments.您当前的代码会将新项目推送到评论中。 You should use update here so you can specify more than one search criteria.您应该在此处使用更新,以便您可以指定多个搜索条件。 This will let you find the element in the comments, but you'll need the comment ID as well as the post ID (otherwise, how are you planning to find the right item from the comments array if more than one are present?)这将让您在评论中找到元素,但您需要评论 ID 以及帖子 ID(否则,如果存在多个评论数组,您打算如何从评论数组中找到正确的项目?)

Post.update(
    {"_id" : req.body.postId, "comments._id": '{the ID of the comment that was liked}',
    {$push:{"comments.$.commentLikes": req._user.id}}
)

This will find the post with the specified ID, find the correct commend depending on who originally posted it, and add the current user's ID to the commentLikes list.这将找到具有指定 ID 的帖子,根据最初发布它的人找到正确的推荐,并将当前用户的 ID 添加到 commentLikes 列表中。 However, like the linked answer states, this is a pretty messy way to handle this and it would likely be better to have a separate collection of comments with an ID pointing back to the post.但是,就像链接的答案状态一样,这是一种非常混乱的处理方式,最好有一个单独的评论集合,其 ID 指向帖子。 Arrays inside of arrays get complicated very fast. arrays 内部的 Arrays 变得非常复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM