简体   繁体   English

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

[英]How do i add/update ObjectId array in a collection using MongoDB(Mongoose)?

This is What I want as a final result. 这是我想要的最终结果。 I have no idea how to update array of indexes. 我不知道如何更新索引数组。

在此输入图像描述

my Schema is built using mongoose 我的架构是使用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}
});

My controllers are: 我的控制器是:

// 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'});
    });
};

Do I need to use a middleware? 我需要使用中间件吗? or do i need to do something in controller? 或者我需要在控制器中做些什么?

What you want is called "population" in Mongoose ( see documentation ), which basically works by storing references to other models using their ObjectId . 你想要的是Mongoose中的“population”参见文档 ),它基本上是通过使用ObjectId存储对其他模型的引用来实现的。

When you have a Post instance and a Comment instance, you can "connect" them like so: 当你有一个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(...);

Your controller would look something like this: 你的控制器看起来像这样:

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' });
      });
    });
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM