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

Keo*_*Kim 3 mongoose mongodb node.js express

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

在此处输入图片说明

我的模式是使用猫鼬构建的

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}
});
Run Code Online (Sandbox Code Playgroud)

我的控制器是:

// 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'});
    });
};
Run Code Online (Sandbox Code Playgroud)

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

rob*_*lep 8

您想要的在Mongoose中称为“填充”请参阅文档),它基本上是通过使用对其他模型的引用来存储它们的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(...);
Run Code Online (Sandbox Code Playgroud)

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

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' });
      });
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

  • @chridam 没必要,猫鼬很聪明 :-) (2认同)