I have been working on a code for a to do list, The issue comes when I actually go to a custom list domain and use the delete method, after deleting the method, the website automatically redirects to "localhost:3000/undefined" and the website fails to respond further, all the functionality stops except the display of the existing elements
This is the node js file
const express=require("express");
const bodyParser=require("body-parser");
const ejs = require('ejs');
const mongoose=require("mongoose")
const app=express();
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/todolsDB");
const itemsSchema=new mongoose.Schema({
toDoToday: String
});
const Item=mongoose.model("Item", itemsSchema);
const itemOne=new Item({
toDoToday: "Wake Up"
});
const itemTwo=new Item({
toDoToday: "Get up"
});
const itemThree=new Item({
toDoToday: "Stand up"
});
const Items=[itemOne,itemTwo, itemThree];
const listSchema = {
name: String,
items: [itemsSchema]
};
const List = mongoose.model("List", listSchema);
app.get("/", function(req, res){
Item.find({}, function(err, Items){
if (Items.length===0){
Item.insertMany(Items, function(err){
if(err){
console.log(err)
}
else{
console.log("Succesfully added!")
}
})
res.redirect("/")
}
else{
res.render("lists .ejs", {Day: "Today", newListItem: Items});
}
})});
app.get("/:topic", function(req, res){
const topic=req.params.topic;
List.findOne({name: topic}, function(err, results){
if (!err){
if (!results){
const list = new List({
name: topic,
items: Items
});
list.save();
res.redirect("/" + topic);
}
else{
res.render("lists .ejs", {Day: results.name, newListItem: results.items});
}
}
});
})
app.post("/",function(request, response){
var itemName=request.body.newElement;
const listName=request.body.list
const item=new Item({
toDoToday: itemName
});
if (listName==="Today"){
response.redirect("/");
item.save();
}else{
List.findOne({name:listName}, function(err, results){
console.log(results)
results.items.push(item)
results.save()
response.redirect("/"+listName);
})
}
})
=
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
if (listName === "Today") {
Item.findByIdAndRemove(checkedItemId, function(err){
if (!err) {
console.log("Successfully deleted checked item.");
res.redirect("/");
}
});
} else {
List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
if (!err){
res.redirect("/" + listName);
}
});
}
});
app.listen(3000, function(){
console.log("connected to port 3000");
})
Here is the "list .ejs" file
<%-include('header.ejs')%>
<body>
<div class="box" id="heading">
<h1>Today is <%= Day %></h1>
</div>
<div class="box">
<% newListItem.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.toDoToday %> </p>
</form>
</div>
<% }) %>
<div>
<form action="/" method="POST" class="item">
<button type="submit" name="list" value=<%= Day %> >+</button>
<input type="text" name="newElement" placeholder="New Element" autocomplete="off">
<input type="hidden" name="listName" id="" value=<%= Day %> > </input>
</div>
</div>
<%-include('footer.ejs')%>
</form>
<script src="" async defer></script>
</body>
</html>
On this route you have req.body.list
app.post("/",function(request, response){
var itemName=request.body.newElement;
const listName=request.body.list
const item=new Item({
toDoToday: itemName
});
And on this route you have req.body.listName
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
Most likely you are trying to access an object which does not exist, so change the property name.
Related
Error: throw er; // Unhandled 'error' event
TypeError: Cannot read properties of null (reading 'items')
at C:\Users\shiva\Desktop\Web Development\todolist\app.js:105:17
getting the error in the 1st app.post method -> else statement. stuck at it for almost a day.
ps: code might not run as db link is changed by me
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb+srv://adminshivam:refd3sfde#cluster0.3igye.mongodb.net/todolistDB");
const itemsSchema = {
name: String
};
const Item = mongoose.model("Item", itemsSchema);
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];
const listSchema = {
name: String,
items: [itemsSchema]
};
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 savevd default items to DB.");
}
});
res.redirect("/");
} else {
res.render("list", {listTitle: "Today", newListItems: foundItems});
}
});
});
app.get("/:customListName", function(req, res){
const customListName = _.capitalize(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;
const listName = req.body.listName;
if (listName === "Today") {
Item.findByIdAndRemove(checkedItemId, function(err){
if (!err) {
console.log("Successfully deleted checked item.");
res.redirect("/");
}
});
} else {
List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
if (!err){
res.redirect("/" + listName);
}
});
}
});
app.get("/about", function(req, res){
res.render("about");
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
error link from above code
foundList.items.push(item);
list.ejs
<%- include("header") -%>
<div class="box" id="heading">
<h1> <%= listTitle %> </h1>
</div>
<div class="box">
<% newListItems.forEach((listItem) => { %>
<form action="/delete" method="post">
<div class="item">
<input type="checkbox" name="checkbox" value="<%= listItem._id %>" onChange="this.form.submit()">
<p><%= listItem.name %></p>
</div>
<input type="hidden" name="listName" value="<%= listTitle %>"></input>
</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") -%>
The problem seems to be at your schema, you are not making it the right way, instead of passing an object to moongose.model like this:
const itemsSchema = {
name: String
};
const Item = mongoose.model("Item", itemsSchema);
You should create a schema with the class Schema from mongoose, so try the following:
const mongoose = require("mongoose");
const { Schema } = mongoose
const itemsSchema = new Schema({
name: {type: String, required: true}
})
const Item = mongoose.model("Item", itemsSchema)
And in your listSchema do the following:
// removed const defaultItems = [item1, item2, item3];
const listSchema = new Schema({
name: {type: String, required: true},
// define an array of id that references the Item schema
items: [{type: ObjectId, ref: "Item", required: true, default: [] }]
});
const List = mongoose.model("List", listSchema);
// the object named as list1 will contain a reference to id of item1, item2 and item3.
const list1 = new List({name: "list1", items: [item1._id, item2._id, item3._id]}).save()
Further up, in your post api :
app.post("/", async function(req, res){
const itemName = req.body.newItem;
const listName = req.body.list;
try {
const item = new Item({ name: itemName });
if (listName === "Today") {
await item.save();
res.redirect("/");
} else {
// save the item id to items field from list schema
const list = await List.findOne({ name: listName })
list.items.push(item._id)
await list.save()
// don't make a redirect within the database query
res.redirect("/" + listName);
}
} catch(err) {
// If some error was threw handle it here
// you can handle mongoose errors as follow:
if(err instanceof mongoose.Error) {
// use a custom message or err.message
res.status(500).json({message: "error with Db"})
}
res.status(500).json({message: "something went wrong"})
}
});
See the docs to know more about it, as you are using references between your schemas I suggest you to take a look at the populate method because probably you will need it in the future. See the available queries from mongoose as well, almost everything you need is at the docs. Hope I helped you!
just remove the space in ejs file
<button type="submit" name="list" value="<%= listTitle %>😒">+</button>
I have my update button that performs a get request to fetch the data with the id and fills the slots. Then, using the form below I perform another get request to send a request to update the data.
<form action="//updateBookRequest" method="GET" id="update-book">
<!-- Book Name -->
<div class="form-group">
<label for="name">Name</label>
<input type="hidden" name="id" value="<%= book._id %> ">
<input type="text" name="name" value="<%= book.name %> " placeholder="The Alchemist">
</div>
<!-- Author Name -->
<div class="form-group">
<label for="author">Author</label>
<input type="text" name="author" value="<%= book.author %> " placeholder="Paulo Coelho">
</div>
<!-- Language -->
<div class="form-group">
<label for="language">Language</label>
<input type="text" name="language" value="<%= book.language %> " placeholder="English">
</div>
<!-- Date -->
<div class="form-group">
<label for="date">Date</label>
<input type="date" name="date" value="<%= book.date %> " placeholder="">
</div>
<div class="form-group">
<div class="buttons">
<button class="btn">Cancel</button>
<button class="btn" type="submit">Save</button>
</div>
</div>
</form>
The route looks like this:
route.get('/update-book', services.updateBook)
And the services.updateBook looks like this:
exports.updateBook = (req, res) => {
axios.put(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
But for some reason, it doesn't update the data.
When I do it in the postman, using the same 'http://localhost:5000/api/books/id', it works just fine and update the data with the postman body as it should.
But, it doesn't when I try to do it in the ejs file with the following section.
I can't seem to find where the problem is. Other functionalities such as adding new data, deleting the data using the id, displaying all the data seem to work fine.
How can I make it to update the data?
This is server.js file:
const express = require('express')
const dotenv = require('dotenv')
const bodyparser = require('body-parser')
const path = require('path')
const connnectDB = require('./server/database/connection')
const app = express()
dotenv.config({path:'config.env'})
const port = process.env.port || 5050
connnectDB()
app.use(bodyparser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use('/css', express.static(path.resolve(__dirname, 'assets/css')))
app.use('/js', express.static(path.resolve(__dirname, 'assets/js')))
app.use('/', require('./server/routes/router'))
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
This is the server/controller/controller.js
const Userdb = require('../model/model')
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({message: 'content can not be empty'})
return
}
const user = new Userdb({
name: req.body.name,
author: req.body.author,
language: req.body.language,
date: req.body.date,
description: req.body.description
})
user
.save(user)
.then(data => {
// res.send(data)
res.redirect('/')
})
.catch(err => {
res.status(500).send({
message: err.message || 'some error occured'
})
})
}
exports.find = (req, res) => {
if (req.query.id) {
const id = req.query.id
Userdb.findById(id)
.then(data => {
if (!data) {
res.status(404).send({message: `error ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: `error ${id}`})
})
} else {
Userdb.find()
.then(user => {
res.send(user)
})
.catch(err => {
res.status(500).send({message:err.message || 'error while finding data'})
})
}
}
exports.update = (req, res) => {
if (!req.body) {
return res.status(400).send({message: 'Data to update is empty'})
}
const id = req.params.id
Userdb.findByIdAndUpdate(id, req.body, {useFindAndModify: false})
.then(data => {
if (!data) {
res.status(404).send({message: `can't update ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: 'err'})
})
}
exports.delete = (req, res) => {
const id = req.params.id
Userdb.findByIdAndDelete(id)
.then(data => {
if (!data) {
res.status(404).send({message: `${id} is wrong`})
} else {
res.send({message: 'user deleted'})
}
})
.catch(err => {
res.status(500).send({message: `could not delete with ${id}`})
})
}
This is server/routes/router.js
const route = express.Router()
const services = require('../services/render')
const controller = require('../controller/controller')
route.get('/', services.homeRoute)
route.get('/add-book', services.addNewBook)
route.get('/update-book', services.updateBook)
route.get('/updateBookRequest', services.updateBookRequest)
route.get('/delete-book', services.deleteBook)
// API
route.post('/api/books', controller.create)
route.get('/api/books', controller.find)
route.put('/api/books/:id', controller.update)
route.delete('/api/books/:id', controller.delete)
module.exports = route
This is server/services/render.js
const axios = require('axios')
exports.homeRoute = (req, res) => {
axios.get('http://localhost:5000/api/books')
.then(function(response) {
res.render('index', {books: response.data})
})
.catch(err => {
res.send(err)
})
}
exports.addNewBook = (req, res) => {
res.render('add_new_book')
}
exports.updateBook = (req, res) => {
axios.get('http://localhost:5000/api/books', {params:{id:req.query.id}})
.then(function(userdata) {
res.render('update_book', {book:userdata.data})
})
.catch(err => {
res.send(err)
})
}
exports.updateBookRequest = (req, res) => {
console.log(req)
axios.put(`http://localhost:5000/api/books/${req.query.id}`, {book:req.body})
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
exports.deleteBook = (req, res) => {
axios.delete(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
console.log('deleted')
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
This is by far the whole code
You need to use a callback in your update function. Also you can use {new: true} to get the updated document.
Userdb.findByIdAndUpdate(id,
req.body,
{useFindAndModify: false},
{new: true},
function (err, data) {
console.log(data); //check if the document is updated
}
})
Also make sure your req.body is an object. if you are unsure, check req.body in console log
this is my post request to save to mongdb database
router.post("/create", async (req, res) => {
const createJottings = new Jottings({
title: req.body.title,
jottings: req.body.jottings
});
try {
await createJottings.save();
res.json(createJottings);
} catch (err) {
res.json({ message: err });
}
});
it works fine on postman but now i am trying to render it using handlebars to the client. this is the form for the client side using handlebars
<div class="card card-body">
<h3>
Edit Jottings/Idea
</h3>
<form action="/jottings/create" method="get">
<div class="form-group">
<label for="title">
Title
</label>
<input type="text" name="title" class="form-control" required />
</div>
<div class="form-group">
<label for="title">
Jottings
</label>
<textarea name="Description" class="form-control" required></textarea>
</div>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
</div>
the form actually loads but when i press submit it doesnt save to mongodb server
{{#each getJottings}}
<div class="card card-body mb-2">
<h4>
{{title}}
</h4>
<p>
{{jottings}}
</p>
<a href="/jottings/edit/{{id}}" class="btn btn-dark btn-block">
Edit
</a>
</div>
{{else}}
<p>
No Ideas and Jottings listed
</p>
{{/each}}
code that outlists saved data in the database if i create it using postman it works but with the form it doesnt.
overview of my jottings route
// Require Mongoose
const router = require("express").Router();
// Setup Models for Jotting
const Jottings = require("../models/jottings.model");
// Setting Endpoints For Routes
// Get All Jottings
router.get("/", async (req, res) => {
try {
const getJottings = await Jottings.find({}).sort({ date: "desc" });
res.render("jottings/index", {
getJottings: getJottings
});
} catch (err) {
res.json({ message: err });
}
});
// Getting routes to set form
router.get("/add", (req, res) => {
res.render("jottings/add");
});
// Get Specific Jottings
router.get("/:id", async (req, res) => {
try {
// Requesting for request paremeter given to ever document created in mongoDB
const id = req.params.id;
await Jottings.findById(id, (err, jottings) => {
if (!id) {
res.json({ message: err });
} else {
res.json(jottings);
}
});
} catch (err) {
res.json({ message: err });
}
});
// Post to create New Jottings for form
router.post("/create", async (req, res) => {
const createJottings = new Jottings({
title: req.body.title,
jottings: req.body.jottings
});
try {
await createJottings.save();
res.json(createJottings);
} catch (err) {
res.json({ message: err });
}
});
router.get("/edit/:id", async (req, res) => {
try {
// Requesting for request paremeter given to ever document created in mongoDB
const id = req.params.id;
const editJottings = await Jottings.findOne({ _id: id });
res.render("jottings/edit", {
editJottings: editJottings
});
} catch (err) {
res.json({ message: err });
}
});
// Patch to Edit Jottings for form
router.patch("/edit/:id", async (req, res) => {
try {
// Requesting for request paremeter given to ever document created in mongoDB
const id = req.params.id;
const editJottings = await Jottings.updateOne(
{ _id: id },
{ $set: { jottings: req.body.jottings } }
);
res.render("jottings/edit", {
editJottings: editJottings
});
} catch (err) {
res.json({ message: err });
}
});
// Delete to delete Jottings for form
router.delete("/delete/:id", async (req, res) => {
try {
// Requesting for request paremeter given to ever document created in mongoDB
const id = req.params.id;
const deleteJottings = await Jottings.deleteOne({ _id: id });
res.json(deleteJottings);
} catch (err) {
res.json({ message: err });
}
});
// Exporting router
module.exports = router;
i would like the details to be saved to the database when i click the submit button and also redirect me to a list of my saved details.
You form uses method GET while you defined router.post to handle form submission.
I'm trying to add a business in Node Express Framework. My issue is that when I fill out the form to add the business, nothing adds to the page. Been trying to figure out this error for some time now.
My business.js code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Business = require('../models/business');
var passport = require('passport');
// set up the GET handler for the main movies page
router.get('/', function(req, res, next) {
// use the Article model to retrieve all movies
Business.find(function (err, business) {
// if we have an error
if (err) {
console.log(err);
res.end(err);
}
else {
// we got data back
// show the view and pass the data to it
res.render('movies/index', {
title: 'Business',
business: business
});
}
});
});
// GET handler for add to display a blank form
router.get('/add', function(req, res, next) {
// new
if (req.isAuthenticated()) {
res.render('movies/add', {
title: 'Add a New Business'
});
}
else {
res.redirect('/auth/login');
}
});
// POST handler for add to process the form
router.post('/add', function(req, res, next) {
// save a new article using our Article model and mongoose
Business.create( {
name: req.body.name,
city: req.body.city,
province: req.body.province,
postal: req.body.postal,
street: req.body.street
}
);
// redirect to main business page
res.redirect('/business');
});
// GET handler for edit to show the populated form
router.get('/:id', function(req, res, next) {
// create an id variable to store the id from the url
var id = req.params.id;
// look up the selected article
Business.findById(id, function(err, business) {
if (err) {
console.log(err);
res.end(err);
}
else {
// show the edit view
res.render('movies/edit', {
title: 'Business Details',
business: business
});
}
});
});
// POST handler for edit to update the article
router.post('/:id', function(req, res, next) {
// create an id variable to store the id from the url
var id = req.params.id;
// fill the article object
var business = new Business( {
_id: id,
title: req.body.title,
content: req.body.content,
date: req.body.date,
rating: req.body.rating,
actor: req.body.actor
});
// use mongoose and our Article model to update
Business.update( { _id: id }, business, function(err) {
if (err) {
console.log(err)
res.end(err);
}
else {
res.redirect('/business');
}
});
});
//get handler for delete using the article id
router.get('/delete/:id', function(req, res, next){
//grab the id parameter from the url
var id = req.params.id;
Business.remove({ _id: id }, function(err) {
if(err) {
console.log(err);
res.end(err);
}
else {
// show updated business page with redirect
res.redirect('/business');
}
});
});
////auth check
//function isLoggedIn(req, res, next) {
// //is the user authenticated>
// if (req.isAuthenticated()) {
// return next();
// }
// else {
// res.redirect('/auth/login');
// }
//}
// make public
module.exports = router;
My add.ejs code:
<%- include ../partials/header.ejs %>
<main>
<form method="post" action="add">
<fieldset>
<label for="name">Name:*</label>
<input type="text" name="name" required />
</fieldset>
<fieldset>
<label for="city">City:*</label>
<input type="text" name="city" required>
</fieldset>
<fieldset>
<p>
<label>Province:*</label>
<select id="province" required>
<option value="--">--</option>
<option value = "ontario">ON</option>
<option value = "quebec">QC</option>
<option value = "british columbia">BC</option>
<option value = "alberta">AL</option>
<option value="nova scotia">NS</option>
<option value="manitoba">MB</option>
<option value="newfoundland">NL</option>
<option value="pei">PEI</option>
</select>
</p>
</fieldset>
<fieldset>
<label for="postal">Postal Code:*</label>
<input type="text" name="postal" required>
</fieldset>
<fieldset>
<label for="street">Street Name:*</label>
<input type="text" name="street" required>
</fieldset>
<button class="btn btn-primary" type="submit">Save</button>
</form>
</main>
</body>
</html>
Thanks so much in advance!
I am using the express-paginate module and I am running into some issues around the res.format section in my routes file. I am wondering why this portion is causing the paginate to not be found when I render my view file.
error message:
ReferenceError: /Users/user/Desktop/Projects/node/blog/views/pages/blog.ejs:7
5|
6| <body>
>> 7|
8| <header>
9| <% include ../partials/header %>
10| </header>
paginate is not defined
at buf.push.
</div>
</div>
</div>
<div class="paginate">
.
</div>
<footer>
.buf (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:34:125)
at eval (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:35:23)
at eval (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:37:67)
at /Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:255:15
at Object.exports.render (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:293:13)
at View.exports.renderFile [as engine] (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:323:20)
at View.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/view.js:76:8)
at Function.app.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/application.js:517:10)
at ServerResponse.res.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/response.js:955:7)
at Object.res.format.html (/Users/user/Desktop/Projects/node/blog/app/routes.js:70:13)
routes.js:
var express = require('express');
var app = express();
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//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
});
});
app.use(paginate.middleware(10, 50));
//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.author = req.body.author; // set the author name
blogpost.content = req.body.content; // set the blog content
blogpost.date = req.body.date; // set the date of the post
//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, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
Blogpost.find(function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
res.format({
html: function() {
res.render('pages/blog', {
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)
}) // END Find Blogpost
}); // END Blogpost.paginate
}); // 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, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
}) // END PUT method
// START DELETE method
.delete(function(req, res) {
Blogpost.remove({
_id: req.params.blogpost_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
paginate.ejs:
<div class="grid">
<div class="col-1-1">
<div class="paginate">
<ul>
<% if (paginate.hasPreiousPages) { %>
<li>
Previous
</li>
<% } %>
<% if (paginate.hasNextPages) { %>
<li>
Next
</li>
<% } %>
</ul>
</div>
</div>
</div>
blog.ejs:
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-1-1">
<div class="body-content">
<% blogpost.forEach(function(blogpost) { %>
<tr>
<td><h2><%= blogpost.title %></h2></td>
<td><h3><%= blogpost.author %></h3></td>
</tr>
<% }); %>
</div>
</div>
</div>
<div class="paginate">
<% include ../partials/paginate %>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
On the second line of your routes.js file, you are calling
var app = express();
This line creates a new express app.
Then you use the paginate middleware on this new app,
This is not the 'running' app, you can find the main app instance in your app.js
All your requests are handled by the app created in app.js, this way the paginare middleware never gets called.
To fix this
1: remove these two lines from routes.js
var app = express();
var paginate = require('express-paginate');
2: add in app.js (before you load your routes)
var paginate = require('express-paginate');
app.use(paginate.middleware(10, 50));
Or if you only want to use pagination for that specific set of routes,
remove
var app = express();
and use
router.use(paginate.middleware(10, 50));