node.js - 更新双重嵌套数组 MongoDB

标签 node.js mongodb mongoose nested-documents

考虑这个架构:

let userSchema = new mongoose.Schema({
id: String,
displayName: String,
displayImage: String,
posts: [
    {
        url: String,
        description: String,
        likes: [String],
        comments: [
            { content: String, date: String, author: { id: String, displayName: String, displayImage: String } }
        ]
    }
]
});

我可以使用此查询从评论数组中删除某个项目

controller.deleteComment = (req, res, next) => {
User.findOneAndUpdate(
    { id: req.query.userid, 'posts._id': req.params.postid, },
    {
        $pull: {
            'posts.$.comments': { _id: req.body.commentID },
        }
    }
)
    .exec()
    .then(() => {
        res.send('deleted');
    })
    .catch(next);
};

我是否可以使用 $set 运算符更新 comments 数组中的元素?我需要根据评论 ID 更改评论的内容..如下所示:

controller.editComment = (req, res, next) => {
    User.findOneAndUpdate(
        { id: req.query.userid, 'posts._id': req.params.postid, 'comments._id':req.body.commentID },
        {
            $set: {
                'posts.$.comments': {  content: req.body.edited },
            }
        }
    )
        .exec()
        .then(() => {
            res.send('deleted');
        })
        .catch(next);
};

这 ^ 显然不起作用,但我想知道是否有办法可以做到这一点?

更新 根据下面的建议,我正在执行以下操作来仅管理一个架构。这是有效的,但是无论我正在编辑哪些帖子评论,只有第一篇帖子的评论会得到更新。我已经检查过,返回文档总是正确的。 doc.save() 方法肯定有问题。

controller.editComment = (req, res, next) => {
User.findOne(
    { id: req.query.userid, 'posts._id': req.params.postid },
    { 'posts.$.comments._id': req.body.commentID }
)
    .exec()
    .then((doc) => {
        let thisComment = doc.posts[0].comments.filter((comment) => { return comment._id == req.body.commentID; });
        thisComment[0].content = req.body.edited;
        doc.save((err) => { if (err) throw err; });
        res.send('edited');
    })
    .catch(next);
};

最佳答案

我不知道一个简单(甚至艰难:P)的方法来实现我想要做的事情。在 mongo 中,双重嵌套数组中的操作相对困难,因此最好避免。

如果您仍然愿意接受架构更改,我建议您为评论创建一个不同的架构,并在用户架构中引用该架构。

因此您的评论架构将如下所示:

let commentSchema = new mongoose.Schema({
     content: String, 
     date: String,
     author: { 
          id: String,
          displayName: String,
          displayImage: String
     }
});

您的用户架构应如下所示:

let userSchema = new mongoose.Schema({
     id: String,
     displayName: String,
     displayImage: String,
     posts: [{
        url: String,
        description: String,
        likes: [String],
        comments: [{
            type: Schema.Types.ObjectId,
            ref: 'comment'   //reference to comment schema
        }]
    }]
});

这样您的数据操作就会容易得多。您可以populate获取用户文档时的评论。并且,请注意更新/删除操作是多么容易,因为您已经知道要更新的评论的 _id。

希望这个答案对您有所帮助!

关于node.js - 更新双重嵌套数组 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43422767/

相关文章:

mongodb - 使用 GridFS - 它应该在一个单独的数据库上吗?

javascript - Node.js module.exports 回调函数?

node.js - AWS EC2 上的 NodeJS : Cannot load public/images folder

javascript - 其他 Cloud Function 调用可以修改全局作用域变量吗?

c# - 使用 MongoDB C# Driver 使用 Regex 查询编写 ElementMatch

node.js - 使用 mongoose 检查 mongodb 中是否存在文档

node.js - 如何在 MongoDB 中为 NodeJS Express 应用程序存储站点配置?

node.js - Mongoose 如何自动将 _id 添加到集合项中数组中的对象?

javascript - 如何使用 Node.js 和 Johnny-Five 解析 'cannot find module ' 串行端口?

javascript - javascript 函数怎么也可以是对象呢?