while editing article, can push it onto author’s array

chooseauthorfromarticle
Matt Huntington 9 years ago
parent 1438f20727
commit 6779ae1bac

@ -1,6 +1,7 @@
var express = require('express');
var router = express.Router();
var Article = require('../models/articles.js');
var Author = require('../models/authors.js')
router.get('/', function(req, res){
Article.find({}, function(err, foundArticles){
@ -35,16 +36,24 @@ router.delete('/:id', function(req, res){
});
router.get('/:id/edit', function(req, res){
Article.findById(req.params.id, function(err, foundArticle){
res.render('articles/edit.ejs', {
article: foundArticle
Author.find({}, function(err, allAuthors){
Article.findById(req.params.id, function(err, foundArticle){
res.render('articles/edit.ejs', {
article: foundArticle,
authors: allAuthors
});
});
});
});
router.put('/:id', function(req, res){
Article.findByIdAndUpdate(req.params.id, req.body, function(){
res.redirect('/articles');
Author.findById(req.body.authorId, function(err, foundAuthor){
Article.findByIdAndUpdate(req.params.id, req.body, {new:true}, function(err, updatedArticle){
foundAuthor.articles.push(updatedArticle);
foundAuthor.save(function(){
res.redirect('/articles');
});
});
});
});

@ -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);

@ -25,6 +25,12 @@
<textarea name="body">
<%=article.body%>
</textarea><br/>
Choose and author:
<select name="authorId">
<% for(var i = 0; i < authors.length; i++) { %>
<option value="<%=authors[i]._id %>"><%=authors[i].name %></option>
<% } %>
</select><br/>
<input type="submit" value="Update Article"/>
</form>
</main>

Loading…
Cancel
Save