【问题标题】:Pushing Nested Object in MongDB在 MongoDB 中推送嵌套对象
【发布时间】: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


    【解决方案1】:

    如果我的理解是正确的,当当前用户喜欢评论时,您会尝试将当前用户的 ID 插入到 commentLikes 数组中。

    Mongo push to array inside array。您当前的代码会将新项目推送到 cmets。您应该在此处使用更新,以便您可以指定多个搜索条件。这将让您在 cmets 中找到元素,但您需要评论 ID 以及帖子 ID(否则,如果存在多个 cmets 数组,您打算如何从 cmets 数组中找到正确的项目?)

    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 列表中。但是,就像链接的答案状态一样,这是一种非常混乱的处理方式,最好有一个单独的 cmets 集合,其 ID 指向帖子。数组内部的数组变得非常复杂。

    【讨论】:

    • 我已经设法从客户端到服务器获取评论 ID,是的,你是对的,我忘记从前端传递评论 ID。
    • 现在 Post.findByIdAndUpdate(req.params.comment_id, { $push: { "cmets.$commentLikes": req.user._id } }, { new: true }).exec((err , 结果) => { if (err) { return res.status(422).json({ error: err }) } else { console.log(result) res.json(result) } })
    • 它返回给我 NULL 你能帮我解决这个问题吗?我收到评论 id
    • 你弄明白了吗?如果您需要获取要插入的元素并对其进行更新,可以使用 findAndUpdate,但不能使用 findByIdAndUpdate,因为您需要一个比 ID 更复杂的过滤器。
    • 不,我想不通,实际上我正在使用 findByIdAndUpdate 删除评论,并将commentLikes 放在它正在工作的 cmets 之外,但是当我喜欢 1 条评论时,它也会更新另一条评论。我面临的唯一问题是在 cmets 中访问 c​​ommentLikes。
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2021-02-23
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多