使用mongoose对子子文档进行CRUD

时间:2016-05-03 02:29:31

标签: node.js mongodb mongoose mean-stack mongoose-schema

我是学习MEAN堆栈的初学者,我正在尝试构建一个基本论坛,以便熟悉这个堆栈。到目前为止,除了子文档之外,我已经完成了所有工作。我在主题内的帖子中对评论做CRUD时遇到了麻烦。我已经做了很多搜索,但看起来并不是我需要的。所以我的问题是,你将如何实现这一点?我知道可能有多种方法可以做到这一点,比如使用ref而不是sub-sub-docs,但看到我已经使用子文档为主题内的CRUD主题和CRUD帖子编写代码,我会如果我不得不返回并更改我的代码,请不要使用引用。

var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var uri = "...";
mongoose.connect(uri);

var CommentSchema = new Schema({
  id: ObjectId,
  content: String,
  author: UserSchema
});

var PostSchema = new Schema({
  id: ObjectId,
  title: String,
  author: UserSchema,
  comments: [CommentSchema]
});

var TopicSchema = new Schema({
  id: ObjectId,
  title: String,
  moderator: UserSchema,
  posts: [PostSchema]
});

var Topic = mongoose.model('Topic', TopicSchema);

var app = express();

app.delete('/topics/:topicId/posts/:postId/comments/:commentId', function(req, res) {
    //What goes here?
});

app.put('/topics/:topicId/posts/:postId/comments/:commentId', function(req, res) {
    //What goes here?
});

app.post('/topics/:topicId/posts/:postId/comments/:commentId', function(req, res) {
    //What goes here?
});

app.get('/topics/:topicId/posts/:postId/comments/:commentId', function(req, res) {
    //What goes here?
});

1 个答案:

答案 0 :(得分:0)

我建议不要太深入地嵌入你的物品。也许创建一个评论集合,它会更方便。 无论如何,如果你想使用一个mongoose操作,你必须先遍历帖子,才能知道你想要更新的索引。我们假设它为0,删除评论:

Topic.findOneAndUpdate(
  { id: req.params.topicId },
  { $pull: { 'posts.0.comments': { _id: req.params._id } }},
  { safe: true }
)

这就是为什么它不是你想要的。

您可以直接更改对象并保存:

Topic.findOne({ _id: req.params.topicId })
  .then(topic => {

    const { posts } = topic
    let comments
    for (let i = 0, l = posts.length; i < l; ++i) {

      if (posts[i]._id.toString() === req.params.postId) {
        comments = posts[i].comments
        for (let j = 0, m = comments.length; j < m; ++j) {
          if (comments[j]._id.toString() === req.params.commentId) {
            comments.splice(j, 1)
            break
           }
        })

        break
      }

    }

    return topic.save()
  })

不太理想,因为它没有利用mongodb索引和研究来进行这些操作。但你可以使用:

const CommentSchema = new Schema({
  id: ObjectId,
  postId: ObjectId,
  content: String,
  author: UserSchema
})

const Comment = mongoose.model('Comment', CommentSchema)

Comment.findOneAndUpdate({ id: req.params.commentId, postId: req.params.postId }, { ... })