Я новичок в NodeJS и пытаюсь создать приложение для форума, используя Angular с возможностью отвечать на комментарии. Я могу добавлять комментарии к посту. Но я не могу добавлять ответы на комментарии к посту. Я думаю, что я делаю что-то не так с моими контроллерами и маршрутами.
По сути, я попытался реализовать функцию reply , посмотрев, как была реализована функция comment для posts , то есть заменил сообщение комментарием, а комментарий - ответить.
Мой index.ejs, здесь я могу добавлять комментарии к посту.
<script type="text/ng-template" id="/posts.html">
..............
<div ng-repeat="comment in post.comments | orderBy:'-upvotes'">
<span style="font-size:20px; margin-left:10px;">
{{comment.body}}
</span>
</div>
<form ng-submit="addComment()" id= "my-form" style="margin-top:30px;">
<h3>Add a new comment</h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Comment" ng-model="body"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
Чтобы реализовать функцию ответа, я добавил следующий код
<div ng-repeat="reply in comment.replies">
<span style="font-size:10px; margin-left:10px;">
{{reply.replytext}}
</span>
</div>
<form ng-submit="addReply()" style="margin-top:20px;">
<h3>Add a new reply</h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Reply" ng-model="replytext"></input>
</div>
<button type="submit" class="btn btn-secondary">Reply</button>
</form>
</div>
до
<form ng-submit="addComment()" id= "my-form" style="margin-top:30px;">
в моем index.ejs. Когда я делаю это, нажатие на кнопку ответа ничего не делает.
Вот что присутствует в моем appAngular.js
app.factory('posts', ['$http', function($http){
var o = {
posts: []
};
.......
o.addComment = function(id, comment) {
return $http.post('/posts/' + id + '/comments', comment);
};
.........
return o;
}]);
app.controller('PostsCtrl', [
'$scope','posts','post',
function($scope, posts, post){
$scope.post = post;
$scope.addComment = function(){
if(!$scope.body || $scope.body === '') { return; }
posts.addComment(post._id, {
body: $scope.body,
author: 'user',
}).success(function(comment) {
$scope.post.comments.push(comment);
});
$scope.body = '';
};
.......
}]);
Я написал код для o.addReply (), похожий на o.addComment (), который я считаю неправильным.
Ниже приведены мои маршруты. Js,
router.post('/posts/:post/comments', function(req, res, next) {
var comment = new Comment(req.body);
comment.post = req.post;
comment.save(function(err, comment){
if(err){ return next(err); }
req.post.comments.push(comment);
req.post.save(function(err, post) {
if(err){ return next(err); }
res.json(comment);
});
});
});
router.param('comment', function(req, res, next, id) {
var query = Comment.findById(id);
query.exec(function (err, comment){
if (err) { return next(err); }
if (!comment) { return next(new Error('can\'t find post')); }
req.comment = comment;
return next();
});
});
Для реализации ответов я добавил в мои маршруты следующие файлы: js
router.post('/posts/:post/comments/:comment/replies', function(req, res, next) {
var comment = new Comment(req.body);
comment.post = req.post;
var reply = new Reply(req.body);
reply.comment = req.comment;
reply.save(function(err, reply){
if(err){ return next(err); }
req.post.comments.comment.replies.push(reply);
req.post.comments.coment.save(function(err, comment) {
if(err){ return next(err); }
res.json(reply);
});
});
});
router.param('reply', function(req, res, next, id) {
var query1 = Reply.findById(id);
query1.exec(function (err, reply){
if (err) { return next(err); }
if (!reply) { return next(new Error('can\'t find comment')); }
req.reply = reply;
return next();
});
});
Наконец, это моя модель мангуста
var CommentSchema = new mongoose.Schema({
body: String,
author: String,
upvotes: {type: Number, default: 0},
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
reply: {type: mongoose.Schema.Types.ObjectId, ref: 'Reply'}
});
.........
var ReplySchema = new mongoose.Schema({
comment: {type: mongoose.Schema.Types.ObjectId, ref: 'Comment'},
replytext: String
});
mongoose.model('Comment', CommentSchema);
mongoose.model('Reply', ReplySchema);