如何使用MongoDB(Mongoose)在集合中添加/更新ObjectId数组?

时间:2015-05-22 14:07:57

标签: node.js mongodb express mongoose

这是我想要的最终结果。我不知道如何更新索引数组。

enter image description here

我的架构是使用mongoose构建的

var postSchema  = new Schema({
    title: {type:String},
    content: {type:String},
    user:{type:Schema.ObjectId},
    commentId:[{type:Schema.ObjectId, ref:'Comment'}],
    created:{type:Date, default:Date.now}
});


var commentSchema  = new Schema({
    content: {type:String},
    user: {type:Schema.ObjectId},
    post: {type:Schema.ObjectId, ref:'Post'}
    created:{type:Date, default:Date.now}
});

我的控制器是:

// api/posts/
exports.postPosts = function(req,res){
    var post = new Post({
        title: req.body.title,
        content: req.body.content,
        user: req.user._id
    });
    post.save(function(err){
        if(err){res.send(err);}
        res.json({status:'done'});
    });
};


// api/posts/:postId/comments
exports.postComment = function(req,res){
    var comment = new Comment({
        content: req.body.content,
        post: req.params.postId,
        user: req.user._id
    });
    comment.save(function(err){
        if(err){res.send(err);}
        res.json({status:'done'});
    });
};

我需要使用中间件吗?还是我需要在控制器中做点什么?

1 个答案:

答案 0 :(得分:6)

你想要的是Mongoose(see documentation)中的“population”,它基本上是通过使用ObjectId存储对其他模型的引用来实现的。

当您拥有Post个实例和Comment个实例时,您可以像这样“连接”它们:

var post    = new Post(...);
var comment = new Comment(...);

// Add comment to the list of comments belonging to the post.
post.commentIds.push(comment); // I would rename this to `comments`
post.save(...);

// Reference the post in the comment.
comment.post = post;
comment.save(...);

您的控制器看起来像这样:

exports.postComment = function(req,res) {
  // XXX: this all assumes that `postId` is a valid id.
  var comment = new Comment({
    content : req.body.content,
    post    : req.params.postId,
    user    : req.user._id
  });
  comment.save(function(err, comment) {
    if (err) return res.send(err);
    Post.findById(req.params.postId, function(err, post) {
      if (err) return res.send(err);
      post.commentIds.push(comment);
      post.save(function(err) {
        if (err) return res.send(err);
        res.json({ status : 'done' });
      });
    });
  });
};