holedata is not defined while loading ejs file after res.render - node.js

I am inserting the data into mongodb and then page rendering to success.ejs. In the success.ejs file I gave one link. When click link in the same success.js file data should fetch from mongodb and show in same success.ejs file. But before loading the success.ejs file after post the data in the console showing holedata is not defined error message.
My post data part in index.js file
app.post('/signingin', function(req, res) {
var item = {
name: req.body.name,
title: req.body.title,
age: req.body.age
};
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('satyamsoft').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('item inserted');
db.close();
});
});
res.render('pages/success');
//console.log(req.body);
});
My success.ejs page
!DOCTYPE html>
<html lang="en">
<% include ../partials/head %>
<title>Post Jobs | Spyeer</title>
<body>
<% include ../partials/nav %>
<section class="get">
<h2>Data Inserted</h2>
Get Data
<div>
<ul>
<% holedata.forEach(function(data) { %>
<li><%= data.this.name %> - <%= data.this.title %> - <%= data.this.age %></li>
<% }); %>
</ul>
</div>
</section>
<% include ../partials/footer %>
<% include ../partials/scripts %>
</body>
</html>
get part code in index.js file
app.get('/getdata', function(req, res){
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('satyamsoft').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
//console.log(resultArray);
//res.render('pages/getdata', {holedata: resultArray});
}, function(){
db.close();
res.render('pages/success', {holedata: resultArray});
});
Please help me advance thanks.

You just need to check every time page render there should be holedata either empty or with data like instead of res.render('pages/success'); you should write res.render('pages/success', {holedata: [] });

Related

How to pass database values from node js to ejs file

Hi I am trying to add search bar in main page and search in the main page without changing to another page.
My user.js file
if (req.method == 'get'){
var username = req.query.username;
Users.find({username}, function (err, user) {
if(err) {
return res.render(template:'index')
}
res.render({template:'index', { user : user}});
})
}
my index.ejs file
<div class="search-user">
<% for user in user { %>
<div>
<p>Username : <%= user.username %></p>
<p>Age <%= user.age %></p>
<p>Status <%= user.status %></p>
</div>
<% } %>
</div>
This is giving me errors. May i know what did i do wrong?
Add a console message and check if you are getting data in user object
if (req.method == 'get'){
var username = req.query.username;
Users.find({username}, function (err, user) {
if(err) {
console.log('error', error)
return res.render('index')
}
console.log('user', user)
res.render('index', { user });
})
}
Further before iterating user of object just check something like this:
<div>
<p>Username : <%= JSON.stringfy(user) %></p>
</div>
By this you will get to know where error is being occured.
Refer to Res.render()
if (req.method == 'get'){
var username = req.query.username;
Users.find({username}, function (err, user) {
if(err) {
return res.render('index')
}
res.render('index', { user });
})
}

What is the proper way to check if id exists or not ? (ejs, mongoose)

If i have code like:
index.js
app.get('/link/:id', (req, res) => {
collection.find({ _id: req.params.id }, (err, collection) => {
if(err) res.send(err)
else {
res.render('link', { collection: collection });
}
link.ejs
<% if(collection != 'undefined') { %>
<li><%= collection.userName %></li>
<li><%= collection.address %></li>
<% }else{ %>
<p>Data not found</p>
<% } %>
But it also shows this error:
error:
Cannot read property 'userName' of undefined
so what is the solution?

How to display all users database (mongodb) details on .ejs file

I have a node.js website that i build with this tutorial:
https://scotch.io/tutorials/easy-node-authentication-setup-and-local
now i want in one of my views to print/display all users data.
in routes.js:
var User = require('../app/models/user'); //the connection to users database
app.get('/profile', isLoggedIn, function (req, res) {
res.render('profile.ejs', {
Users: User // get the user out of session and pass to template
});
});
and this is in my profile.ejs file:
<ul>
<% Users.forEach( function(err, user) { %>
<li><%= user %> </li>
<% }); %>
i get an error: "undefined is not a function" because of the <% Users.forEach( function(err, user) { %> line
what am i doing wrong?
You need to actually query the user collection via the model's find() query function which will return an array of user documents when executed, i.e.
var User = require('../app/models/user'); //the connection to users database
app.get('/profile', isLoggedIn, function (req, res) {
User.find({}).exec(function(err, users) {
if (err) throw err;
res.render('profile.ejs', { "users": users });
}
});
then render the list of user documents in your profile.ejs as:
<% users.forEach(function (user) { %>
<li>
<h1><%= user.name %></h1>
</li>
<% }) %>

Error: can't set header after they are sent

I have two schemas, one for user and one for friendship system (follow system)
module.exports = mongoose.model('User', {
email: {
type: String,
unique: true,
lowercase: true
},
password:String,
profile: {
fullname: String,
gender: String,
role: {type: String, default: 'Autorizado'},
country: String },
});
and this for friend system
module.exports = mongoose.model('Friendship', {
follower: String,
followed: String
});
I'm using passport to auth my users... the problem is that I want lo load the user information and the friend information related to the user globally using res.locals I make this happen using 2 functions in login post route....
router.post('/login', userController.postLogin,friendController.getFollow);
this is my postlogin function
exports.postLogin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
req.flash('errors', { msg: info.message });
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) return next(err);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect('/');
});
})
(req, res, next);
};
When I try to execute this code everything goes fine but when I log in I get the header error please how can I solved this or other way to get the user and follow information and use it in every view?.
EDIT 3: only works in the next two views
Single User page
<%= info.profile.fullname %>
<br>
<%= info.email %>
<br>
<%= info.profile.country %>
<br>
<%= user.follow %>
<br>
<% if(user && (user._id != info.id)){ %>
<br>
<form action="/follow/<%= info._id %>" method="post">
<button type="submit">Follow</button></form>
<%}%>
<br>
atras
List of Registered User
<%if (user) {%>
<h1>Hola <%= user.profile.fullname %> </h1>
<%}%>
<br>
<% users.forEach(function (user) {%>
<p><%= user.profile.fullname %></p>
<%});%>
Home
This is my index and in this view the user.follow doesn't work
<%if (!user) {%>
sign up
<br>
login
<%} else { %>
<h1>Hola <%= user.profile.fullname %> Eres lo Maximo</h1>
perfil
<br>
Logout
<br>
<%}%>
<br>
Lista de Usuarios
EDIT 4: new deserializeUser config.
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
FF.find({ follower:id }, function(err, follow) {
user.follow = follow;
});
done(err, user);
});
});
EDIT 5: This is my route code
router.get('/', function(req, res) {
res.render('index');
});
router.get('/login', userController.getLogin);
router.post('/login', userController.postLogin);
router.get('/logout', userController.logout);
router.get('/signup', userController.getSignup);
router.post('/signup', userController.postSignup);
router.get('/profile', passportConf.isAuthenticated, userController.getAccount);
router.post('/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
You had friendController.getFollow which would've worked only for the request of '/login' page, so the follow object wouldn't have been persistently available on other routes. To fix that you had to put all that code inside the passport.deserializeUser function.
Inside the passport.deserializeUser function you could only call done once so you had to put the logic to find follow inside the callback of User.find so that you could attach follow to user.
This allowed you to remove the friendController.getFollow from your '/login' route which I think was the cause of your error.

res.format.html not working with paginate module

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

Resources