【问题标题】:How do i add/update ObjectId array in a collection using MongoDB(Mongoose)?如何使用 MongoDB(Mongoose)在集合中添加/更新 ObjectId 数组?
【发布时间】:2015-05-22 22:27:47
【问题描述】:

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

我的 Schema 是使用 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'});
    });
};

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    你想要的在 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' });
          });
        });
      });
    };
    

    【讨论】:

    • 在线post.commentIds.push(comment);不应该是post.commentIds.push(comment._id);吗?
    • @chridam 没必要,猫鼬很聪明 :-)
    • 这个问题是如果 postId 不存在会触发错误,但无论如何都会保存评论
    • @J.Correa 是的,如果帖子不存在,您必须清理刚刚保存的评论,或者反过来:首先找到帖子,如果它存在,保存并添加评论。
    • 是的,你可以使用链式承诺来完成这项工作,这是我现在正在做的事情:o
    猜你喜欢
    • 2020-05-10
    • 2022-01-23
    • 1970-01-01
    • 2021-07-21
    • 2016-02-27
    • 2018-08-21
    • 2012-10-15
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多