Node.js SELECT*FROM a table in a SQL database - javascript

My problem is that I can enter data from my input boxes into an SQL table, but the problem is that the text from the table will not show on the page i want to. What works is that the playlist page will show the a href links depending on how many playlists i have made just not the text.
I have left out the database details for security reasons.
playlist.jade
extends layout
block content
h1= title
p Welcome to #{title}
h1 My Playlists
br
a(href='/login') Login
br
a(href='/users/createPlaylist') Create a new Playlists
br
a(href='/users/playlistCreated') test
br
for playlist, i in playlists
a(href='/users/playlistCreated') | #{playlist.text}
br
users.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
router.get('/createPlaylist', function(req, res, next) {
res.render('new_playlist');
});
router.get('/playlistCreated', function(req, res, next) {
res.render('name_of_created_playlist');
});
router.get('/songCreated', function(req, res, next) {
res.render('song_page');
});
router.get('/newSong', function(req, res, next) {
res.render('new_song');
});
router.post('/newPlaylist', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var playlist = {
text: req.body.thePlaylist
};
dbConnection.query('INSERT INTO Playlists (playlist_name) VALUES(?)', [playlist.text], function(err, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
playlist.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(playlist));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
router.post('/newSongAdded', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
var song = {
text: req.body.theSong,
url: req.body.theSongURL
};
dbConnection.query('INSERT INTO Songs (song_name, song_url) VALUES(?,?)',[song.text, song.url], function(err, results,fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
if (err) {
throw err;
}
// notice that results.insertId will give you the value of the AI (auto-increment) field
song.id = results.insertId;
// Going to convert my joke object to a JSON string a print it out to the console
console.log(JSON.stringify(song));
// Close the connection and make sure you do it BEFORE you redirect
dbConnection.end();
res.redirect('/');
});
});
});
module.exports = router;
index.js
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var dbConnectionInfo = {
host : '',
user : '',
password : '',
database : 'audio_collections'
};
/* GET home page. */
router.get('/login', function(req, res, next) {
res.render('login');
});
router.post('/login', function(req, res, next) {
var username = req.body.username;
username = username.trim();
if (username.length == 0) {
res.redirect('/login');
}
else {
req.session.username = username;
res.redirect('/');
}
});
router.get('/', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Playlists', function(err, results, fields){
if (err) {
throw err;
}
var allPlaylists = new Array();
for (var i = 0; i < results.length; i++) {
var playlist = {
id: results[i].id,
text: results[i].text
};
console.log(JSON.stringify(playlist));
allPlaylists.push(playlist);
}
dbConnection.end();
res.render('playlists', {playlists: allPlaylists});
});
router.get('/users/playlistCreated', function(req, res, next) {
var dbConnection = mysql.createConnection(dbConnectionInfo);
dbConnection.connect();
dbConnection.on('error', function(err) {
if (err.code == 'PROTOCOL_SEQUENCE_TIMEOUT') {
// Let's just ignore this
console.log('Got a DB PROTOCOL_SEQUENCE_TIMEOUT Error ... ignoring ');
} else {
// I really should do something better here
console.log('Got a DB Error: ', err);
}
});
dbConnection.query('SELECT * FROM Songs', function(err, results, fields){
if (err) {
throw err;
}
var allSongs = new Array();
for (var i = 0; i < results.length; i++) {
var song = {};
song.id = results[i].id;
song.text = results[i].text;
song.url = results[i].url;
console.log(JSON.stringify(song));
allSongs.push(song);
}
dbConnection.end();
res.render('name_of_created_playlist', {songs: allSongs});
});
});
});
module.exports = router;
new_playlist.jade
extends layout
block content
form(method='POST', action='/users/newPlaylist')
div
label(for='thePlaylist') Name of Playlist
div
textarea(type='text', name='thePlaylist')
br
input(type='submit', name='Add new Playlist')
a(href='/') Cancel
Here is the database and table setups
database and table setup
I would really appreciate the help and I have been stuck on this for a week now.

Got it fixed I didnt need the for loops inside my array
Only needed var allPlaylist = results; Since results is an array already

Related

MEAN Stack application: Toggle boolean value

I am using mlab and mongojs along with Angular. When I attempt to toggle a boolean value (onStatus), the button in the view toggles from off to on, but it crashes the app. When I check in the DB the property has been removed from the document. Code snippets below:
device.service.ts
toggleDevice(updatedStatus){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.put('/api/device/'+updatedStatus._id, JSON.stringify(updatedStatus), {headers: headers})
.map(res => res.json());
}
devices.component.ts
toggleDevice(device){
var currentStatus = device.onStatus;
var updatedStatus = {
_id: device._id,
name: device.name,
onStatus: !currentStatus
};
this.deviceService.toggleDevice(updatedStatus)
.subscribe(data => {
device.onStatus = !device.onStatus
});
}
devices.compoonents.html
<button class="btn" (click)="toggleDevice(device)" type="button">{{ device.onStatus ? 'Switch Off' : 'Switch On' }}</button>
API routing
var express = require('express');
var router = express.Router();
var database = require('../config/database');
var mongojs = require('mongojs');
var db = mongojs(database.url, ['devices'])
// GET : All devices
router.get('/devices', function(req, res, next){
db.devices.find(function(err, devices){
if(err) {
res.send(err);
}
res.json(devices);
});
});
// GET : Single device
router.get('/device/:id', function(req, res, next){
db.devices.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
}
res.json(device);
});
});
// POST : Save a device
router.post('/device', function(req, res, next){
var device = req.body;
device.onStatus = false;
if(!device.name) {
res.status(400);
res.json({
"error": "Please add a name."
});
} else {
db.devices.save(device, function(err, device){
if(err) {
res.send(err);
}
res.json(device);
});
}
});
// DELETE : A device
router.delete('/device/:id', function(req, res, next){
db.devices.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
}
res.json(device);
});
});
// PUT : Update a device
router.put('/device/:id', function(req, res, next){
var device = req.body;
var updatedDevice = {};
if(device.name) {
updatedDevice.name = device.name;
}
if(!updatedDevice){
res.status(400);
res.json({'Error': 'Name not specified'});
} else {
db.devices.update({_id: mongojs.ObjectId(req.params.id)}, updatedDevice, {}, function(err, device){
if(err) {
res.send(err);
}
res.json(device);
});
}
db.devices.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
}
res.json(device);
});
});
module.exports = router;
Errors
/home/chopin/Development/homeautomation/node_modules/mongojs/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/home/chopin/Development/homeautomation/node_modules/express/lib/response.js:719:10)
at ServerResponse.send (/home/chopin/Development/homeautomation/node_modules/express/lib/response.js:164:12)
at ServerResponse.json (/home/chopin/Development/homeautomation/node_modules/express/lib/response.js:250:15)
at /home/chopin/Development/homeautomation/routes/devices.js:80:9
at /home/chopin/Development/homeautomation/node_modules/mongojs/lib/collection.js:50:5
at handleCallback (/home/chopin/Development/homeautomation/node_modules/mongojs/node_modules/mongodb/lib/utils.js:95:56)
at /home/chopin/Development/homeautomation/node_modules/mongojs/node_modules/mongodb/lib/cursor.js:674:5
at handleCallback (/home/chopin/Development/homeautomation/node_modules/mongojs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:171:5)
at nextFunction (/home/chopin/Development/homeautomation/node_modules/mongojs/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:682:5)
[nodemon] app crashed - waiting for file changes before starting...
Thanks for any help.
EDIT: I should mention the error only occurs the 2nd time I toggle the button. I am assuming as this has been removed from DB for some reason. The name of and ID persist, yet the onStatus doesn't.
EDIT 2: Full code https://github.com/Sacki2013/homeAutomation
You are trying send the response even after it is already sent. All you have to do is that add return statements after your response is sent.
var express = require('express');
var router = express.Router();
var database = require('../config/database');
var mongojs = require('mongojs');
var db = mongojs(database.url, ['devices'])
// GET : All devices
router.get('/devices', function(req, res, next){
db.devices.find(function(err, devices){
if(err) {
res.send(err);
return;
}
res.json(devices);
});
});
// GET : Single device
router.get('/device/:id', function(req, res, next){
db.devices.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
return;
}
res.json(device);
});
});
// POST : Save a device
router.post('/device', function(req, res, next){
var device = req.body;
device.onStatus = false;
if(!device.name) {
res.status(400);
res.json({"error": "Please add a name."});
} else {
db.devices.save(device, function(err, device){
if(err) {
res.send(err);
return;
}
res.json(device);
});
}
});
// DELETE : A device
router.delete('/device/:id', function(req, res, next){
db.devices.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
return;
}
res.json(device);
});
});
// PUT : Update a device
router.put('/device/:id', function(req, res, next){
var device = req.body;
var updatedDevice = {};
if(device.name) {
updatedDevice.name = device.name;
}
if(!updatedDevice){
res.status(400);
res.json({'Error': 'Name not specified'});
} else {
db.devices.update({_id: mongojs.ObjectId(req.params.id)}, updatedDevice, {}, function(err, device){
if(err) {
res.send(err);
return;
}
/*
* Commenting following line because
* you are sending a response in `findOne`
*/
// res.json(device);
db.devices.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, device){
if(err) {
res.send(err);
return;
}
res.json(device);
});
});
}
});
module.exports = router;
On your /device/:id PUT endpoint you're doing the update and findOne calls asynchronously, independent from each other, so res.json() is called twice. Try moving your findOne function inside the update callback.

node js express - querying the price field

Im having trouble figuring out how to query the price. My current attempt is not working and im not sure what you have to type in the local host.
http://localhost:3000/priceSearch?
I have implemented - orderSearch.find({price:{$gt:400, $lt: 700}})
the price field in my mongodb is a number not a a string
Thank you:D
Here is my code:
priceSearch.ejs
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/WishList';
router.get('/', function (req, res) {
var price = req.query.price;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log("Unable to connect to the server", err);
} else {
console.log("Connection established...");
var orderSearch = db.collection('orders');
// find document who satisify price
orderSearch.find({price:{$gt:400, $lt: 700}}).toArray(function (err, result) {
if (err) {
res.send(err);
} else if (result.length) {
res.render('priceSearch',
{
priceSearch: result,
title: 'Product price search',
}
);
} else {
res.send("No documents found");
}
db.close();
});
}
});
});
module.exports = router;
req.query.price;
i added a stupid var to it

TypeError: Cannot read property 'regenerate' of undefined

I'm new to node.js and trying to use 'express-session' to create and storage a session, the title is the bug, and below is my code. I check the origin code on github, but didn't find any question. pls help, thank you so much.
User.prototype.login = function (req, res, next) {
pool.getConnection(function (err, connection) {
// 获取前台页面传过来的参数
var user_name = req.param("user_name"),
password = req.param('password');
// 建立连接,向表中插入值
var select = mysql.format(user_command.login, user_name);
connection.query(select, function(err, result) {
if(result) {
if(result[0].password === password){
req.session.regenerate(function() {
if(err){
res.json({ret_code: 2, ret_message:'登陆失败' });
}
res.sessionID = user_name;
res.json({ret_code: 0, ret_msg: '登录成功'});
});
}else {
res.redirect('/login');
}
}
// 释放连接
connection.release();
});
});
};
Express middleware are executed in the order that you define them. Your problem is that you have set app.use('./', routes) before app.use(session(...)).
To fix this, just move the first line after the second.
app.use(session({
// ...
});
app.use('./', routes);

Some of my routes don't work in express

I'm trying to create a tic-tac-toe game and want to save the user data into a database, but my problem is that the router I want to do this with can't be reached, I get an 'Internal server error message(500)'.
Here is the index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Lab5' });
});
//check if server is online
router.get('/alive', function(req, res, next) {
res.send('alive');
});
router.post('/alive', function(req, res) {
//here I generate the next step for the game
});
//this route can't be reached
router.get('/db', function(res, req) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({}, {}, function(e, docs) {
res.send(JSON.stringify(docs));
});
});
//and this route can be reached
router.post('/db', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
var username = req.body.username;
var gameStatus = req.body.gameStatus;
try {
if(Object.keys(req.body).length !== 0 && JSON.stringify(req.body) !== JSON.stringify({})){
console.log("Data insert...");
collection.insert({
"username" : username,
"gameStatus" : gameStatus
}, function (err, docs) {
if(err) {
res.send("Error inserting data into database!");
}
});
}
} catch(err) {
console.log("Error in insert: " + err);
}
});
module.exports = router;
Here is the getDB.js:
function getDB() {
var xhttp = createRequest();
if(xhttp === null) {
alert("Ajax object not supported by your browser!");
}
else {
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText != null) {
var db = JSON.parse(xhttp.responseText);
console.log(db);
}
}
}
xhttp.open('GET', 'db', true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send();
}
}
My problem is with
router.get('/db', function() {...});
and the
router.post('/db', function() {...});
works just fine, it inserts the sent data into database.
Any help would be appreciated!
Seems that you forgot to import the mongodb bindings for express.
https://www.npmjs.com/package/express-mongo-db

How can you remove all documents from a collection with Mongoose?

I know how to...
Remove a single document.
Remove the collection itself.
Remove all documents from the collection with Mongo.
But I don't know how to remove all documents from the collection with Mongoose. I want to do this when the user clicks a button. I assume that I need to send an AJAX request to some endpoint and have the endpoint do the removal, but I don't know how to handle the removal at the endpoint.
In my example, I have a Datetime collection, and I want to remove all of the documents when the user clicks a button.
api/datetime/index.js
'use strict';
var express = require('express');
var controller = require('./datetime.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
module.exports = router;
api/datetime/datetime.controller.js
'use strict';
var _ = require('lodash');
var Datetime = require('./datetime.model');
// Get list of datetimes
exports.index = function(req, res) {
Datetime.find(function (err, datetimes) {
if(err) { return handleError(res, err); }
return res.json(200, datetimes);
});
};
// Get a single datetime
exports.show = function(req, res) {
Datetime.findById(req.params.id, function (err, datetime) {
if(err) { return handleError(res, err); }
if(!datetime) { return res.send(404); }
return res.json(datetime);
});
};
// Creates a new datetime in the DB.
exports.create = function(req, res) {
Datetime.create(req.body, function(err, datetime) {
if(err) { return handleError(res, err); }
return res.json(201, datetime);
});
};
// Updates an existing datetime in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Datetime.findById(req.params.id, function (err, datetime) {
if (err) { return handleError(res, err); }
if(!datetime) { return res.send(404); }
var updated = _.merge(datetime, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, datetime);
});
});
};
// Deletes a datetime from the DB.
exports.destroy = function(req, res) {
Datetime.findById(req.params.id, function (err, datetime) {
if(err) { return handleError(res, err); }
if(!datetime) { return res.send(404); }
datetime.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
};
function handleError(res, err) {
return res.send(500, err);
}
DateTime.remove({}, callback) The empty object will match all of them.
.remove() is deprecated. instead we can use deleteMany
DateTime.deleteMany({}, callback).
In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.
Source: Mongodb.
If you are using mongo sheel, just do:
db.Datetime.remove({})
In your case, you need:
You didn't show me the delete button, so this button is just an example:
<a class="button__delete"></a>
Change the controller to:
exports.destroy = function(req, res, next) {
Datetime.remove({}, function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
}
);
};
Insert this ajax delete method in your client js file:
$(document).ready(function(){
$('.button__delete').click(function() {
var dataId = $(this).attr('data-id');
if (confirm("are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/',
success: function(response) {
if (response == 'error') {
console.log('Err!');
}
else {
alert('Success');
location.reload();
}
}
});
} else {
alert('Canceled!');
}
});
});
MongoDB shell version v4.2.6
Node v14.2.0
Assuming you have a Tour Model: tourModel.js
const mongoose = require('mongoose');
const tourSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A tour must have a name'],
unique: true,
trim: true,
},
createdAt: {
type: Date,
default: Date.now(),
},
});
const Tour = mongoose.model('Tour', tourSchema);
module.exports = Tour;
Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster.
I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.
const mongoose = require('mongoose');
const Tour = require('./../../models/tourModel');
const conStr = 'mongodb+srv://lord:<PASSWORD>#cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then((con) => {
console.log(`DB connection successful ${con.path}`);
});
const deleteAllData = async () => {
try {
await Tour.deleteMany();
console.log('All Data successfully deleted');
} catch (err) {
console.log(err);
}
};
Your_Mongoose_Model.deleteMany({}) can do the job
References:
https://mongoosejs.com/docs/api.html#query_Query-deleteMany
https://www.geeksforgeeks.org/mongoose-deletemany-function/

Categories

Resources