I have been building out a tagging system for my ExpressJS application and I have been able to create my routing to pick up on the individual tags that are used for my record, but the issue I am running into is trying to display content associated with the selected tag. For instance a record has a tag "Mouse", when clicked the route correctly goes to /tag/mouse, but I'm not sure if I should use a loop within my template to display only those values or if I should really be using a method within my route. I'm currently using nothing and the value being displayed on the tag page is undefined. I have a feeling the route method is what I am looking for.
Here is the main focus of my routes file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
console.log(req.body.tags);
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags.trim().split(","); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
function getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.get('/tag/:blogpost_tags', function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/tag', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
Model:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
featureImage: String,
blogUrl: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: Array, lowercase: true },
date: { type: Date, default: Date.now() }
});
BlogPostSchema.post('init', function (post) {
var date = new Date(post.date || Date.now() );
post.dateString = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
Tag page (EJS):
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="container">
<div class="col-md-12">
<%= blogpost.tags %>
</div>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
Related
I learning how to create a to-do list web app. I encounter some problems when I want to add some new items into custom list, my console log this warnings: Cannot read property 'items' of null.
Another problem is, when I enter a new custom list after /, the new custom list should be shown as a title on the current page (the violet part), but it never show at all.
I do read some Q&A which is related to this course. Mostly the answer is they have extra space in value="<%= listTitle %>", which is the code inside ejs file. (I'll show my code later)
My code shown as below, as you can see there are not any extra space in value="<%= listTitle %>". So I literally cannot figure out what is the problem.
<%- include("header") -%>
<div class="box" id="heading">
<h1><%= listTitle %></h1>
</div>
<div class="box">
<% newListItems.forEach(function(item) { %>
<form action="/delete" method="post">
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form.submit( )">
<p><%=item.name%></p>
</div>
</form>
<% }) %>
<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button type="submit" name="list" value="<%= listTitle %>">+</button>
</form>
</div>
<%- include("footer") -%>
And this is my js file:
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
//create & connect database
mongoose.connect("mongodb://localhost: 27017/todolistDB", {
useNewUrlParser: true,
useUnifiedTopology: true
});
//create mongoose schema
const itemsSchema = {
name: String
};
//create model
const Item = mongoose.model("Item", itemsSchema);
//create documents & put them into array
const item1 = new Item({
name: "Welcome to your todolist!",
});
const item2 = new Item({
name: "Hit the + button to add a new item.",
});
const item3 = new Item({
name: "<-- Hit this to delete an item.",
});
const defaultItems = [item1, item2, item3];
//create a new schema for custon name list
const listSchema = {
name: String,
items: [itemsSchema]
};
//create a new model for custon name list
const List = mongoose.model("List", listSchema);
app.get("/", function(req, res) {
Item.find({}, function(err, foundItems) {
if (foundItems.length === 0) {
Item.insertMany(defaultItems, function(err) {
if (err) {
console.log(err);
} else {
console.log("Successfully saved default iems to Database");
}
});
res.redirect("/");
} else {
res.render("list", {listTitle: "Today", newListItems: foundItems});
}
});
});
app.get("/:customListName", function(req, res) {
const customListName = req.params.CustomListName;
List.findOne({name: customListName}, function(err, foundList) {
if (!err) {
if (!foundList) {
//Create a new list
const list = new List({
name: customListName,
items: defaultItems
});
list.save();
res.redirect("/" + customListName);
} else {
//Show an existing list
res.render("list", {listTitle: foundList.name, newListItems: foundList.items});
}
}
});
});
app.post("/", function(req, res) {
const itemName = req.body.newItem;
const listName = req.body.list;
const item = new Item({
name: itemName
});
if (listName === "Today") {
item.save();
res.redirect("/");
} else {
List.findOne({name: listName}, function(err, foundList) {
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
});
}
});
app.post("/delete", function(req, res) {
const checkedItemId = req.body.checkbox; //.checkbox is from ejs list
Item.findByIdAndRemove(checkedItemId, function(err) {
if (!err) {
console.log("Successfully deleted checked item!");
res.redirect("/");
}
});
});
app.get("/about", function(req, res) {
res.render("about");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
Hope that anyone can help out with my questions. Thanks!
There is an issue in the post handler. First of all, foundList is coming empty, and you are checking items on it which throws an error. Check why it is coming empty. Secondly, foundList.save() won't work, you need to create an instance for this and then call save method on it.
Check the List collection data why it is not saving anything. When you get the list follow the above steps.
app.post("/", function(req, res) {
const itemName = req.body.newItem;
const listName = req.body.list;
const item = new Item({
name: itemName
});
if (listName === "Today") {
item.save();
res.redirect("/");
} else {
// make sure listName is correct
List.findOne({name: listName}, function(err, foundList) {
foundList.items.push(item); --> Issue is here
foundList.save();
res.redirect("/" + listName);
});
}
});
I am posting this answer as I can't explain these things in the comments.
I have my node routes as below
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
//var morgan = require('morgan'); // log requests to the console (express4)
//var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override');
var fs = require('fs');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = require('./models/users');
var Dummy = require('./models/dummycar');
//app.use(express.static(__dirname + '/')); // set the static files location /public/img will be /img for users
//app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
// get users list
app.get('/api/users',function(req, res) {
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
//create users
app.post('/api/users', function(req, res) {
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err) {
if (err)
res.send(err);
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
});
//create cars
app.post('/api/cars', function(req, res) {
var dummy = new Dummy();
dummy.name = req.body.name;
dummy.brand = req.body.brand;
dummy.class = req.body.class;
dummy.price = req.body.price;
dummy.available = req.body.available;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("sucess");
});
});
//list cars
app.get('/api/cars',function(req, res) {
Dummy.find(function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
//list cars by available
app.get('/api/cars/available',function(req, res) {
Dummy.find({available:'true'},function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by class
app.get('/api/cars/:classtype',function(req, res) {
Dummy.find({class:req.params.classtype}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by price
app.get('/api/cars/price/:startvalue/:endvalue',function(req, res) {
Dummy.find({price:{$gte:req.params.startvalue,$lte:req.params.endvalue}}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// booking option by sending date and name
app.get('/api/cars/book/:nametype',function(req, res) {
Dummy.findOne({name:req.params.nametype}, function(err, dummy) {
if (err)
res.send(err);
dummy.available = false;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("updated");
});
});
});
// user authentication
app.get('/api/users/:usernametype/:passwordtype',function(req, res) {
User.findOne({$and:[{username:req.params.usernametype},{password:req.params.passwordtype}]}, function(err, user) {
if (err)
res.send(err);
else {
if (user == null)
res.send(false);
else
res.send(true);
}
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
//app.use('/api', router);
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./view/intro.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('server running on ' + port);
My model are
//dummycar.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dummySchema = new Schema({
name: {
type: String,
required: true
},
brand: {
type: String
},
class: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
available: {
type: Boolean,
required: true
},
dateavailable: {
type: Date,
default:Date.now }
});
module.exports = mongoose.model('Dummy', dummySchema);
//user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
But i don't how to call them from angular.js
I have my intro.html as below
<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title>Starter Node and Angular</title>
<!-- CSS -->
<link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css"> <!-- custom styles -->
<!-- JS -->
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<!-- ANGULAR CUSTOM -->
<script src="js/controllers/MainCtrl.js"></script>
<script src="js/controllers/NerdCtrl.js"></script>
<script src="js/services/NerdService.js"></script>
<script src="js/appRoutes.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="sampleApp" ng-controller="NerdController">
<div class="container">
<!-- HEADER -->
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="/">Stencil: Node and Angular</a>
</div>
<!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
<ul class="nav navbar-nav">
<li>Nerds</li>
</ul>
</nav>
<!-- ANGULAR DYNAMIC CONTENT -->
<div ng-view></div>
</div>
</body>
</html>
I would like to call them when user click each link. If some one could help me developing angularjs services.
Best would be to create a service but you can do it in the ctrl aswell
// users.service.js
var userService = angular.module('app.userService', ['ngResource'])
.factory('users', function ($http, $q) {
var that = this;
this.data = {};
var url = '';
var factory = {
get: get
};
function get() {
url = '/api/users';
var defer = $q.defer();
$http.get(url).
success(function (data, status, headers, config) {
defer.resolve(data);
}).
error(function (data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
};
});
// some.controller.js
angular.module('app.somectrl', ['app.userService'])
.controller(someController);
function someController(userService) {
userService.get().then(function (res) {
// do sth
}, function (err) {
// handle error
});
}
I am trying since 3 hours to store the data from html form to mongodb using noddejs.
while clicking on submit it shows another page which returns the data which has been submitted in json format but it is not being stored in database.
This is my app.js:
app.use(serveStatic(__dirname+"/index.html")).listen(8080);
var mongoUri = 'mongodb://localhost/test';
//Note that I am changing the dbname and trying to store data in different //db will also shows the same error
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + mongoUri);
});
console.log("connection successfull");
app.use(express.bodyParser());
app.use(express.static(__dirname + "/" ));
app.use(bodyParser.urlencoded({extended:true}));
app.post('/InquiryDetails', function(req,res){
res.json(req.body);
console.log(req.body);
});
require('./models/InquiryDetails');
app.listen(4000);
console.log('Listening on port 4000...');
this is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myskyllSchema = new Schema({
name: String,
email: String,
state: String,
country: String,
school: String,
profession: String,
phone: Number
});
mongoose.model('InquiryDetails', myskyllSchema);
This is my controller:
var mongoose = require('mongoose'),
InquiryDetails = mongoose.model('InquiryDetails');
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
Any help will be appreciated.
Just replace the code in app.js :
app.post('/InquiryDetails', function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
res.send(req.body);
});
});
instead of :
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
The reason is controller was unable to load and method add is not registered with post method. Now it is working.
I am trying to be able to update my content via my editor, but I'm wondering what part of my application I should be modifying to be able to do this. I have a feeling that it is through the route file, but was wondering if there was a hyperlink method that I should be using from within my view to be able to generate my view with the content I want to edit.
Here is my route file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
var AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
var S3_BUCKET = process.env.S3_BUCKET;
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
}); // END GET method
router.get('/sign_s3', function(req, res){
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.s3_object_name,
Expires: 60,
ContentType: req.query.s3_object_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
}
else{
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.s3_object_name
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
//portfolio
router.get('/portfolio', function(req, res) {
res.render('pages/portfolio');
});
//login
router.route('/login')
.get(function(req, res) {
res.render('pages/login.ejs', {
message: req.flash('loginMessage')
});
})
.post(passport.authenticate('local-login', {
successRedirect : '/admin',
failureRedirect : '/login',
failurFlash : true
}));
//sign up
/*
router.route('/signup')
.get(function(req, res) {
res.render('pages/signup.ejs', {
message: req.flash('signupMEssage')
});
})
.post(passport.authenticate('local-signup', {
successRedirect : '/admin',
failureRedirect : '/signup',
failurFlash : true
}));
*/
//admin dashboard
router.get('/admin', isLoggedIn, function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/admin', {
user: req.user,
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
//logout
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
//middleware to make sure user is logged in
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
Blogpost.ejs (Where I'm trying to create a link to edit the post):
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Admin</h1>
<h2>Welcome user <%= user.local.email %></h2>
Logout
</div>
<div class="row">
<!-- LOCAL INFORMATION -->
<div class="col-sm-6">
<h3>New Post</h3>
<div class="well">
<h3><span class="fa fa-user"></span> Local</h3>
<p>
<strong>id</strong>: <%= user._id %><br>
<strong>email</strong>: <%= user.local.email %><br>
</p>
</div>
<h3><u>Published Blogposts</u></h3>
<% blogpost.forEach(function(blogpost) { %>
<h4><%= blogpost.title %> Edit</h4>
<% }); %>
</div>
</div>
</div>
</body>
</html>
I am trying to use the PUT method to update a record in my database, but I am running into a issue where the object is not defined.
ReferenceError: blogpost is not defined
I am referencing this tutorial with my routing steps and noticed that despite the variable being defined in my /blogs route, meaning that it is local to that function, that in the tutorial, they don't define the variable again when routing their put method. They simply call the object's property that they plan to update. Is there a reason why I'm not able to access this object? Is it a scope issue?
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
//index
router.route('/')
.get(function(req, res) {
var drinks = [
{ name: 'Bloody Mary', drunkness: 3 },
{ name: 'Martini', drunkness: 5 },
{ name: 'Scotch', drunkness: 10}
];
var tagline = "Lets do this.";
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
//blog
router.route('/blog')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.content = req.body.content; // set the blog content
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res) {
Blogpost.find(function(err, blogs) {
if (err)
res.send(err);
res.json(blogs);
});
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
res.json(blog);
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
Specific area where the issue is created:
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
Should be:
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {