From 78b9069072d2f23549fcc0ef95e3e08ea4690bc2 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Tue, 22 Nov 2016 22:09:39 +0100 Subject: [PATCH] push articles onto author --- controllers/authors.js | 21 ++++++++++++++++++--- models/authors.js | 4 +++- views/authors/edit.ejs | 36 ++++++++++++++++++++++++++++++------ views/authors/show.ejs | 8 ++++++++ 4 files changed, 59 insertions(+), 10 deletions(-) diff --git a/controllers/authors.js b/controllers/authors.js index 4301ebe..6e9c51d 100644 --- a/controllers/authors.js +++ b/controllers/authors.js @@ -1,5 +1,6 @@ var express = require('express'); var Author = require('../models/authors.js'); +var Article = require('../models/articles.js'); var router = express.Router(); router.get('/', function(req, res){ @@ -41,9 +42,23 @@ router.put('/:id', function(req, res){ }); router.get('/:id/edit', function(req, res){ - Author.findById(req.params.id, function(err, foundAuthor){ - res.render('authors/edit.ejs', { - author: foundAuthor + Article.find({}, function(err, foundArticles){ + Author.findById(req.params.id, function(err, foundAuthor){ + res.render('authors/edit.ejs', { + author: foundAuthor, + articles: foundArticles + }); + }); + }); +}); + +router.post('/:id/articles', function(req, res){ + Article.findById(req.body.articleId, function(err, foundArticle){ + Author.findById(req.params.id, function(err, foundAuthor){ + foundAuthor.articles.push(foundArticle); + foundAuthor.save(function(){ + res.redirect('/authors/' + req.params.id + '/edit'); + }) }); }); }); diff --git a/models/authors.js b/models/authors.js index 673ff6b..2d3cd75 100644 --- a/models/authors.js +++ b/models/authors.js @@ -1,7 +1,9 @@ var mongoose = require('mongoose'); +var Article = require('./articles.js'); var authorSchema = mongoose.Schema({ - name: String + name: String, + articles: [Article.schema] }); var author = mongoose.model('Author', authorSchema); diff --git a/views/authors/edit.ejs b/views/authors/edit.ejs index 024247c..4cecb10 100644 --- a/views/authors/edit.ejs +++ b/views/authors/edit.ejs @@ -13,17 +13,41 @@ Home
  • - Authors Index + <%=author.name%>'s Show Page
  • -

    Author Attributes:

    -
    -
    - -
    +
    +

    Author Attributes:

    +
    +
    + +
    +
    +
    +

    Articles Written By This Author

    +
      + <% for(var i = 0; i < author.articles.length; i++) { %> +
    • <%=author.articles[i].title%>
    • + <% } %> +
    +
    +
    +

    Articles Not Written By This Author

    +
      + <% for(var i = 0; i < articles.length; i++) { %> +
    • + <%=articles[i].title%> +
      + + +
      +
    • + <% } %> +
    +
    diff --git a/views/authors/show.ejs b/views/authors/show.ejs index 3282028..83c855d 100644 --- a/views/authors/show.ejs +++ b/views/authors/show.ejs @@ -25,6 +25,14 @@
  • Name: <%=author.name%>
  • +
    +

    Articles Written By This Author

    + +
    Edit