Wimal Weerawansa Wimal Weerawansa - 6 months ago 10
AngularJS Question

Mean.js Query var not working

Im using Mean.js to create a blog, i installed it with npm, and i create crud module comment to comment each article, and i save some comment with

article
id as reference. and i create api route in server.

// Comments Routes
app.route('/api/comments/:articleId').all()
.get(comments.listbyArticle);


on server cotroller

exports.listbyArticle = function(req, res) {

Comment.find( {article : req.articleId }).sort('-created').populate('user', 'displayName').exec(function(err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};


but when navigate to this route

http://localhost:3000/api/comments/57550c21612bc90478333017


it response all comments except this article id, if i hard code (
'57550c21612bc90478333017'
) the article id instead of
req.articleId
.Then response shows me proper comments.

please explain me what is wrong?

Answer

You should use req.params to access the articleId in the URL:

exports.listbyArticle = function(req, res) {
    var articleId = req.params.articleId;
    Comment.find( {article: articleId }).sort('-created')
           .populate('user', 'displayName')
           .exec(function(err, comments) {
                if (err) {
                    return res.status(400).send({
                        message: errorHandler.getErrorMessage(err)
                    });
                } else {
                    res.jsonp(comments);
                }
            });
};