更新双嵌套数组MongoDB
考虑这个模式:
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 } } ] } ] });
我能够使用此查询从comments数组中删除某个项目
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); };
这显然不工作,但我想知道是否有办法我可以做到这一点?
更新根据以下build议,我正在做以下事项来pipe理只有一个架构。 这工作,但是只有第一篇文章的评论得到更新,无论我正在编辑哪些post评论。 我已经检查过,退货文件总是正确的。 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中,在双重嵌套的arrays中操作相对困难,因此最好避免。
如果您仍然对模式更改开放,则build议您为注释创build不同的模式,并在用户模式内引用该模式。
所以你的评论模式将如下所示:
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 }] }] });
这样你的数据操作就会容易得多。 您可以在获取用户文档时填充注释。 而且,请注意更新/删除操作是多么容易,因为您已经知道要更新的注释的_id。
希望你find这个答案有帮助!
controller.editComment = (req, res, next) => { User.findOneAndUpdate( { id: req.query.userid, 'posts._id': req.params.postid, 'comments._id':req.body.commentID }, { $push: { 'posts.$.comments': { content: req.body.edited }, } } ) .exec() .then(() => { res.send('deleted'); }) .catch(next); };