如何获取对象ID以及如何更新

时间:2017-02-12 02:41:58

标签: node.js mongodb

我正在尝试获取db中已有文章的对象ID,这样我就可以在发表评论之前验证文章是否存在。

问题出在路由器上(/ blog / article / comment)。我无法从/ blog / article /:postid获取文章对象ID。我想把这个id传递给articleId:

articleId: req.params.postid 

我也尝试过:

articleId: req.article._id

模型结构:comment.js

var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
  content: { type: String },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  articleId: { type: mongoose.Schema.Types.ObjectId, ref:'Article' },
  dateCommented: { type: Date, default : Date.now }
});

文章模型:article.js

var ArticleSchema = new mongoose.Schema({
  category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
  commentId:{type: mongoose.Schema.Types.ObjectId, ref:'Comment'},
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  blog: [{
    topic: { type: String, unique: false, lowercase: true },
    body: {  type: String, unique: false, lowercase: true },
    tags: [ 'first', 'mongodb', 'express'],
    created: Date,
    modified: { type : Date, default : Date.now },
    state: {  type: String, unique: false, lowercase: true }
    }]
});

main.js

router.param('postid', function(req, res, next, id) {
  if (id.length !=24) return next(new Error ('The post id is not having the correct length'));
    //articleId: req.param('postid'),
  Article.findOne({ _id: ObjectId(id)}, function(err, article) {
    if (err) return next(new Error('Make sure you provided correct post id'));
    req.article = article;
    next();
  });
});

router.get('/blog/article/:postid', function (req, res, next) {
  Article.findById({ _id: req.params.postid }, function (err, article) {
    if (err) return next(err);
    res.render('main/publishedArticle', {
      article: article
    });
  });
});


router.post('/blog/article/comment', function(req, res, next) {
  async.waterfall([
    function(callback) {
      var comment = new Comment({
        articleId: req.params.postid,
        content: req.body.content,
        user: req.user._id
      });

        comment.save(function(err) {
          if (err) return next (err);
          req.flash('success', 'Thank you for your comment');
          callback(err, comment);
        });
    },
    function(comment) {
      Article.update({_id : comment.articleId }, { $set: { commentId: {} }}, function(err, updated) {
        if (updated) {
          res.redirect('/')
        }
      });
    }
  ]);

});

我遇到的另一个问题是如何更新文章中每条评论的commentId

Article.update({_id : comment.articleId }, { $set: { commentId: {} }}, function(err, updated)

1 个答案:

答案 0 :(得分:1)

由于/blog/article/comment路由是一个帖子请求。只需在该请求的正文中提交您的articleId即可。你必须从客户端发送它。您可以使用req.body.articleID访问它(如果这就是您所谓的变量)。

有关节点中POST请求的详细信息,请参阅here

关于你的第二个问题:

在您的文章架构中,您有commentId,这是一条记录。你想要的是一系列评论。像这样:

comments: [{type: mongoose.Schema.Types.ObjectId, ref:'Comment'}]

然后在你的代码中......

...
function(comment) {
  //comment should contain all the comments 

  //Grab the article
  Article.findOne({ _id: comment.articleId}, function(err, article){

    //Go through all the comments in 'comment' compare them with the ones in artcle.comments.
      //The ones that aren't already in the article object get put into newComments...
    var newComments = [];

    Article.update({ _id: comment.articleId }, { $addToSet: { comments: newComments } }, function(err, updated) {
    if (updated) {
      res.redirect('/')
    }
  });
  });
}
...

我没有完全实现代码,但它应该让你开始正确。

addToSet Documentation Some more examples of add to set