Advertisement
braveheart1989

Add Comments

May 27th, 2017
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mongoose = require('mongoose')
  2. const allModules = require('../custom_modules/all-needed-modules')
  3. require('../models/Article')
  4. let Article = mongoose.model('Article')
  5. require('../models/Comment')
  6. let Comment = mongoose.model('Comment')
  7. let addComment = (req, res) => {
  8.   // Method POST
  9.   req.pathname = req.pathname || allModules.url.parse(req.url).pathname
  10.   let urlId = req.pathname.split('/')[3]
  11.   let body = ''
  12.   req.on('data', (data) => {
  13.     body += data
  14.   })
  15.   req.on('end', () => {
  16.     let parsedBody = allModules.query.parse(body)
  17.     let comment = new Comment({
  18.       articleID: urlId,
  19.       content: parsedBody.comment,
  20.       date: Date.now()
  21.     })
  22.     Article
  23.       .findByIdAndUpdate(urlId)
  24.       .then(article => {
  25.         article.comments.push(comment)
  26.         article.save()
  27.       }).then(() => {
  28.         comment
  29.         .save()
  30.         .catch(err => console.log(err))
  31.       })
  32.     Article
  33.       .find({_id: urlId})
  34.       .then(articles => {
  35.         console.log(articles)
  36.         for (let article of articles) {
  37.           Comment
  38.             .find({articleID: article._id})
  39.             .then((article) => {
  40.               allModules.fs.readFile('./views/image-details.html', (err, data) => {
  41.                 if (err) allModules.errorHandler.throwError(err)
  42.                 res.writeHead(200, {'Content-Type': 'text/html'})
  43.                 data = data.toString()
  44.                 console.log(article)
  45.                 res.write(allModules.mustache.render(data, {Comments: article}))
  46.                 res.end()
  47.                 return
  48.               })
  49.             })
  50.         }
  51.       })
  52.       .catch(err => console.log(err))
  53.   })
  54. }
  55.  
  56. module.exports = addComment
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement