簡體   English   中英

在 MongDB 中推送嵌套的 Object

[英]Pushing Nested Object in MongDB

我想從 Mongo Schema 訪問嵌套元素。 我想要做的是當用戶喜歡用戶ID的評論時,如果我將commentLikes作為單獨的父級,則應該將用戶ID的評論推送到commentLikes數組中,該數組是評論的子項評論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) }) }

我只是想訪問后端評論中的commentLikes,我知道我的邏輯是正確的

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

我也嘗試通過comments[commentLikes] 訪問commentLikes,但它給了我一個錯誤。

如果我理解正確,那么當當前用戶喜歡評論時,您會嘗試將當前用戶的 ID 插入到 commentLikes 數組中。

請參閱Mongo push to array inside array 您當前的代碼會將新項目推送到評論中。 您應該在此處使用更新,以便您可以指定多個搜索條件。 這將讓您在評論中找到元素,但您需要評論 ID 以及帖子 ID(否則,如果存在多個評論數組,您打算如何從評論數組中找到正確的項目?)

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

這將找到具有指定 ID 的帖子,根據最初發布它的人找到正確的推薦,並將當前用戶的 ID 添加到 commentLikes 列表中。 但是,就像鏈接的答案狀態一樣,這是一種非常混亂的處理方式,最好有一個單獨的評論集合,其 ID 指向帖子。 arrays 內部的 Arrays 變得非常復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM