Trying to Eliminate Players in a Tournament via button - node.js

I am trying to implement the update route into a poker site I am building. I have been able to get the players to appear on the show page but I would like to update the mongo DB from inTournament: "Yes" to inTournament: "No" when the Eliminate button is selected for that player. I have included my code below. Thank you, in advance, for any help with this.
======================= app.js UPDATE ROUTE=======================
app.get("/seating", function(req, res){
//Get all players from poker_DB
Seat.find({inTournament: "Yes"}, function(err, allseats){
if(err){
console.log(err);
} else {
shuffle(allseats);
res.render("seating", {seats: allseats});
}
});
});
//Update player's tournament status
app.put("/seating", function(req, res){
Seat.findByIdAndUpdate(req.params.id, req.params.inTournament, function(err, updatedStatus){
if(err) {
console.log(err);
} else {
res.send("Data Updated");
}
});
});
======================= SHOW PAGE=======================
<div class ="row text-left" style="display:flex; flex-wrap: wrap;">
<div class="col-md-4 table table-bordered">
<h3 class="text-center">Table 1</h3>
<ol>
<% var i = 1; %>
<% var j = 0; %>
<% seats.forEach(function(seat){ %>
<% if(seat.player && i < perTable1){ %>
<% console.log(perTable2); %>
<li><%= seats[j].player %>
<form action"/seating?_method=PUT" method="POST">
<button class="btn btn-sm btn-warning" type="Submit">Eliminate</button>
</form>
</li>
<% i++ %>
<% j++ %>
<% } else { %>
<% j++ %>
<% } %>
<% return j; %>
<% }); %>
</ol>
</div>
</div>

Related

Can't get name from req.user.name to output in Nodejs

your text <%= post.user.name %> show TypeError in ejs file
this is my post_controller:-
this is error show in web page
const Post = require('../models/post'); module.exports.home = function (req, res) {
// populate the user of each post
Post.find({}).populate('user').exec(function (err, posts) {
return res.render ('home', {
title: "Home",
posts: posts
});
})
}
This is my home.ejs file part:-
<ul>
<% for(post of posts){ %>
<li>
<%= post.content %>
<br>
<%= post.user.name %>
</li>
<% } %>
</ul>

Cannot read property 'contentType' of undefined

I'm creating facebook like social media app using nodejs and ejs. I'm getting error " Cannot read property 'contentType' of undefined". But I get this error on profile.ejs and not on newsfeed.ejs. profile.ejs render photo if there's photo in the post but if I post a post with text only,this "Cannot read property 'contentType' of undefined" error occur.
app.js
app.get("/newsfeed", function(req, res){
if(req.isAuthenticated()){
Post.find({}, function(err, foundItem){
if(err){
console.log(err);
} else {
const loggedUser = req.user;
res.render("newsfeed", {posts: foundItem, loggedUser: loggedUser, foundUser: "undefined"});
}
}).sort({date: -1});
} else {
res.redirect("/login");
}
});
app.get("/profile/:userProfile", function (req, res) {
const userId = req.params.userProfile;
const loggedUser = req.user
if(req.isAuthenticated){
User.findById(userId, function(err, foundUser){
if(err){
console.log(err);
} else {
res.render("profile", {foundUser: foundUser, loggedUser:loggedUser});
}
}).sort({date: -1});
}
})
newsfeed.ejs
<% posts.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } %>
<hr>
<% }); %>
profile.ejs
<% foundUser.post.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined" || post.img != null || post.img != "") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } else { %>
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="#" class="image" onerror="this.style.display='none'">
</div>
<% } %>

Mongoose doesnt save multiline string

When i try to put a multiline string into a mongoose database it doesnt want to work. It just saves one line of the string.
Logging content to console:
Website result:
EJS Code
<% posts.forEach(function(post){ %>
<div class="card mb-2" style="width: 100%;">
<div class="card-body">
<% if(user.admin == true || user.id == post.authorid){ %>
<form action="/deletepost/<%= post.id %>" method="post">
<button type="submit" class="btn btn-sm btn-danger btn-block">Delete</button>
</form>
<br>
<% } %>
<h5 class="card-title"><%= post.authorname %></h5>
<h6 class="card-subtitle mb-2 text-muted"><%= post.date %></h6>
<hr>
<p class="card-text"><%= post.content %></p>
</div>
</div>
<% }); %>
Mongoose model:
const PostSchema = new mongoose.Schema({
content: {
type: String
}
})
How i save to database:
var newPost = {content, authorid, authorname};
Post.create(newPost, function(err, newlyCreated){
if(err){
console.log(err);
} else {
res.redirect("/app")
}
});
I use express & ejs if that matters.

Html datalist option through JavaScript in node js

I want to pass data from MySQL database in datalist option. My application is written in express js using ejs view. I can't figure out how to pass database values to list in JavaScript and how to pass this list to ejs file.
add.js:
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT shipper_names.Shipper_ID, shipper_names.Shipper_Name FROM shipper_names";
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
title: "Add Product",
shipper_names: results[0],
message: ''
});
});
}
}
EJS file:
<!doctype html>
<html lang="en">
<div>
<a class="float-right" href="/" title="Home">Home</a>
</div>
<div class="contnainer">
<% if (message) {%>
<p class="text-container text-danger">
<%= message %>
</p>
<%}%>
<% if (shipper_names) {%>
<form class="add-player-form" action="" method="POST" enctype="multipart/form-data">
<div>
<input type="text" id="shippers_names" list="languageList" />
<!--your input textbox-->
<datalist id="languageList">
<option value=""> </option>
</datalist>
</div>
<button type="submit" class="btn">Add Product</button>
</form>
<% } else { %>
<p class="text center">Product Not Found. Go HereTo Add Product.</p>
<% } %>
</div>
</html>
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT * from shipper_names"
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
shipper_names: results
});
});
},
<div>
<input type="text" id="txtAutoComplete" list="names" />
<!--your input textbox-->
<datalist id="names">
<% shipper_names.forEach((shipper_names, index)=>{%>
<option id=<%= shipper_names.Shipper_ID%>>
<%= shipper_names.Shipper_Name%></option>
<%})%>
</datalist>
</div>
this is working

extract data from html table to nodejs post request

I fill html table with data from database (user's emails and their roles in my system (admins and users)).
router.get('/adminOffice', function(req, res){
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
res.render('adminOffice', {rows: rows});
});
});
With the help of ejs it looks next (adminOffice.ejs):
<form method="post" action="saveRoles">
<table name="table" id="table"><tr>
<th>Email</th><th>Role</th>
</tr>
<% for (var i = 1; i < rows.length; i++) { %>
<tr class="tableclass">
<td><%= rows[i].email %></td>
<td> <select class="select">
<% if (rows[i].role == 'admin') { %>
<option selected value="admin">admin</option>
<option value='user'>user</option>
<% } else { %>
<option selected value="user">user</option>
<option value="admin">admin</option>
<% } %>
</select>
</tr>
<% } %>
</table>
<input type="submit" name="submit" value="submit" />
</form>
If I want to change some user's role I need to extract the data from table to JSON format for example in post request, how can I do this?
I tried to use request and cheerio
router.post('/saveRoles', function(req, res, next){
request.get('http://127.0.0.1:3000/adminOffice', function(err,
response, body, callback){
var $ = cheerio.load(body);
var result = $(".tableclass").map((i, element) => ({
email: $(element).find('td:nth-of-type(1)').text(),
role: $(element).find('.select option:selected').text()
})).get();
console.log(result[0].role);
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
for(var i = 1; i < rows.length; i++){
if(rows[i].role != result[i-1].role){
database.connection.query("update users set role = ? where email = ?", rows[i].role, rows[i].email, function(err, res){
if(err) console.log(err);
console.log("success");
});
} else {
console.log("not success");
}
}
});
});
res.redirect('/adminOffice');
});
but they works with new /adminOffice page and with initial values there.
For example there're 2 users in my table: {email: user1#user, role: user}, {email: user2#user, role: user}, I change role of 1st user to admin and press sumbit, request loads new adminOffice page where 1st user again has role user so post logs double not success and DB never changed.
Maybe I should use AJAX or smth else (new to NodeJS and JS)
Changed html code:
<form method="post" action="/saveRoles">
<% for (var i = 1; i < rows.length; i++) { %>
<div class="form-group">
<label for="changingRole"> <%= rows[i].email %></label>
<select name="role">
<% if (rows[i].role == 'admin') { %>
<option selected value='admin'>admin</option>
<option value="user">user</option>
<% } else { %>
<option selected value="user">user</option>
<option value="admin">admin</option>
<% } %>
</select>
</div>
<% } %>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
so I can easy now extract roles and work with them further
router.post('/saveRoles', urlencodedParser, function(req, res, next){
var roles = req.body;
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
for(var i = 1; i < rows.length; i++){
console.log(rows[i].role);
console.log(roles.role[i-1]);
if(rows[i].role != roles.role[i-1]){
database.connection.query("update users set role = ? where email = ?", [roles.role[i-1], rows[i].email],
function(err, res){
if(err) console.log(err);
console.log("success");
});
} else {
console.log("not changed");
}
}
});
res.redirect('/adminOffice');
});

Resources