Guest User

Untitled

a guest
May 21st, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. //CREATE CAMPGROUND ROUTE - add new campground to database.
  2. router.post("/", middleware.isLoggedIn, function(req, res){
  3. var name = req.body.name;
  4. var price = req.body.price;
  5. var image = req.body.image;
  6. var description = req.body.description;
  7. var author = {
  8. id: req.user._id,
  9. username: req.user.username
  10. };
  11.  
  12. var newCampground = {name: name, price: price, image: image, description: description, author: author};
  13.  
  14. //Create a new campground and save to database.
  15. Campground.create(newCampground, function(err, campground){
  16. if(err){
  17. req.flash("error", "There was an error adding your campground to the database: " + err.message);
  18. res.redirect("/campgrounds");
  19. } else {
  20. req.flash("success", "Your campground has been successfully added!");
  21. res.redirect("/campgrounds");
  22. }
  23. });
  24. });
  25.  
  26. //CREATE COMMENTS ROUTE
  27. router.post("/", middleware.isLoggedIn, function(req, res){
  28. Campground.findById(req.params.id, function(err, campground){
  29. if(err){
  30. req.flash("error", "There was an error finding the campground you wish to comment on in the database: " + err.message);
  31. res.redirect("/campgrounds");
  32. } else {
  33. Comments.create(req.body.comment, function(err, comment){
  34. if(err){
  35. req.flash("error", "There was an error adding your comment to the database: " + err.message);
  36. res.redirect("back");
  37. } else {
  38. //Add user ID and username to comment.
  39. comment.author.id = req.user._id;
  40. comment.author.username = req.user.username;
  41.  
  42. //Save the comment with user ID and username.
  43. comment.save();
  44.  
  45. //Add comment to the campground.
  46. campground.comments.push(comment._id);
  47. campground.save();
  48. req.flash("success", "Your comment has been successfully added!");
  49. res.redirect("/campgrounds/" + campground._id);
  50. }
  51. });
  52. }
  53. });
  54. });
Add Comment
Please, Sign In to add comment