1

I am trying to obtain the object id for any article already in db so that I can validate that the article exists before comments are made.

The issue is on the router (/blog/article/comment). I cannot get the article object id from /blog/article/:postid. I want to pass this id to articleId like this:

articleId: req.params.postid 

I have also tried:

articleId: req.article._id

model structure: 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 model: 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('/')
        }
      });
    }
  ]);

});

Another issue I have is how to update the commentId for each comment in the Article

Article.update({_id : comment.articleId }, { $set: { commentId: {} }}, function(err, updated)
CODI
  • 147
  • 4
  • 17
  • For the second question, do you want to add a bunch of comment IDs to the article? Is that what your asking how todo? – matt Feb 12 '17 at 02:48
  • Yes, I want each comment id to be saved to the article that is commented on – CODI Feb 12 '17 at 04:02
  • See my answer for the additions I added. It should get you off to the right start. :) – matt Feb 12 '17 at 04:19
  • Thanks @Treeless, this did not save the article id from article model to articleId. Is there something I am missing? I need the article object id (_id) that is stored in mongodb to be saved as articleId in the comment – CODI Feb 12 '17 at 04:34
  • My code is incorrect I think. comment is an array is it not? If so, comment[0].articleId should be what you need. – matt Feb 12 '17 at 04:42
  • Treeless, the articleId from red.body.articleId is not grabbing the article id (_id) from Mongo db or the postid. So comment.articleId is empty in DB. That's my first issue – CODI Feb 12 '17 at 04:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135481/discussion-between-treeless-and-codi). – matt Feb 12 '17 at 05:04

1 Answers1

1

Since the /blog/article/comment route is a post request. Just submit your articleId in the body of that request. You'll have to send it up from the client. You can access it with req.body.articleID (If that is what you call the variable).

See here for more info on POST requests in node.

For your second question:

Within your article schema you have commentId, That is a single record. What you want is an array of comments. Something like this:

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

Then within your code...

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

I didn't fully implement the code, but it should get you off to the right start.

addToSet Documentation Some more examples of add to set

Community
  • 1
  • 1
matt
  • 1,680
  • 1
  • 13
  • 16