Following this tutorial, when running my server.js file I am getting the following error
self.s.pool = new Pool(Object.^assign(self.s.options, options, {bson:this.s.
TypeError: undefined is not a function
"
Seems to be a problem with my db.open() function. However, I am unsure as to whether it is because a connection can not be made to the database or something else.
I can log the server and db objects, so not sure where the undefined error is coming from. It doesn't log the error message contained in the db.open function so something seems to break before then.
Any help would be great, below is my code
server.js
var express = require('express'),
movies = require('./routes/movies.js');
var app = express();
app.configure(function(){
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
app.get('/movies',movies.findAll);
app.get('/movies/:id',movies.findById);
app.post('/movies', movies.addMovie);
app.put('/movies/:id',movies.updateMovie);
app.delete('/movies/:id',movies.deleteMovie);
app.listen(3000);
console.log('Listening on port 3000...');
routes/movies.js
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('moviedb', server);
db.open(function(err,db){
if(!err)
{
console.log('Connected to "moviesdb" database');
db.collection('movies',{strict:true},function(err,collection){
if(err)
{
console.log("The 'movies' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findAll = function(req,res){
db.collection('movies',function(err,collection){
collection.find().toArray(function(err,items){
res.send(items);
});
});
}
exports.findById = function(req,res){
var id = req.params.id;
console.log('Retrieving movie: ' + id);
db.collection('movies',function(err,collection){
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err,item){
res.send(item);
});
});
}
exports.addMovie = function(req,res){
var movie = req.body;
console.log('Adding movie: ' + JSON.stringify(movie));
db.collection('movies',function(err,collection){
collection.insert(movie,{'safe':true},function(err,result){
if(err)
{
res.send({'error':'An error has occurred'});
}
else
{
console.log('Success:' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
exports.updateMovie = function(req,res){
var id = req.params.id,
movie = req.body;
console.log('Updating movie: ' + id);
console.log(JSON.stringify(movie));
db.collection('movies',function(err,collection){
collection.update({'_id':new BSON.ObjectID(id)},movie,{'safe':true},function(err,result){
if(err)
{
console.log('Error updating movie: ' + err);
res.send({'error':'An error has occured'});
}
else
{
console.log('' + result + ' document(s) updated');
res.send(movie);
}
});
});
}
exports.deleteMovie = function(req,res){
var id = req.params.id;
console.log('Deleting movie: ' + id);
db.collection('movies',function(err,collection){
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
if(err)
{
res.send({'error':'An error has occurred - ' + err});
}
else
{
console.log('' + result + ' document(s) deleted');
res.send(req.body);
}
});
});
}
/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
var populateDB = function() {
var movies = [
{
name: "Titanic",
release: "2009",
description: "description....",
picture: "titanic-poster.jpg"
},
{
name: "Jaws",
release: "2000",
description: "description....",
picture: "jaws-poster.jpg"
},
{
name: "Halloween",
release: "1992",
description: "description....",
picture: "halloween-poster.jpg"
}
];
db.collection('movies', function(err, collection) {
collection.insert(movies, {safe:true}, function(err, result) {});
});
}
Related
So here I have a big problem: I need to create an array that stores an SQL value, in a json file (the code is below). The thing is, where do I declare the query, or what extra should I add to make it work properly? I have created the function viewMontadora, and it works normally when I run the server, listing all the car makers registered in SQL, with all their info. I'm still not very familiar with node.js.
app.use(express.static(__dirname + '/library'))
app.listen(port, () => {
console.log(`Servidor online em
http://localhost:${port}`)
})
app.get('/', (req, res) => {
res.render('pages/home')
})
app.get('/about', (req, res) => {
function viewMontadora() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM VIEW_PRODUTOS").then(function (recordset) {
res.contentType('application/json');
res.send(JSON.stringify(recordset));
console.log(recordset);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
return viewMontadora();
})
app.get('/contact', (req, res) => {
res.render('pages/contact')
})
app.post('/contact', (req, res) => {
res.send('Obrigado por entrar em contato conosco, ' + req.body.name + '!Responderemos em breve!')
})
app.post('/client', (req, res) => {
// Lista de Utilizadores
var usersValid = [{
username: 'SELECT [RazaoSocial] FROM [SITE].[dbo].[Clientes]',
email: 'SELECT [Email] FROM [SITE].[dbo].[Clientes]'
}, ];
console.log(usersValid);
var error = [{
id: 1,
ErrorLogin: 'Usuario não identificado'
}];
usersValid.push({
username: req.body.name,
email: req.body.email
});
for (var i = 0; i < usersValid.length; i++) {
if (usersValid[i].username === req.body.name && usersValid[i].email ===
req.body.email) {
var dataClient = [{
nameClient: req.body.name,
emailClient: req.body.email,
imgClient: 'http://lmdsneto.000webhostapp.com/images/user.png'
}]
res.render('pages/client', {
dataClients: dataClient
})
//res.send('Bem vindo, ' + req.body.name + ' Email ' +
req.body.email
} else {
res.send(error);
}
}
});
On a high level you need to receive a email and password from the client Eg. Browser, then you need to confirm if that username and password exist in your db. if then do then you can say that they are a valid user.
So aside from security concerns about storing passwords in plain text you should be able to just simply do this: (Obviously just change any values for the user id that you need)
app.post('/client', (req, res) => {
// place userInfo into an object
var userInfo = {
email: req.body.name,
password: req.body.password
};
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM FROM [SITE].[dbo].[Clientes] WHERE email = " +
userInfo.email +
" AND password = " +
userInfo.password).then(function (selectedUser) {
// if we have one selected user we know it is valid
if (selectedUser.length === 1) {
// user is valid
} else {
// user is not valid
}
});
}).catch(function (err) {
console.log(err);
});
});
what i trying to do here is query to mysql database, but when i execute my query, it just loading forever, no error untill it timed out, how to solve this? below is my db.js code :
Db.js :
var mysql = require("mysql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new mysql.createConnection(settings.dbConfig);
conn.connect(function(err){
if(err){
console.log(err + "1");
return;
}
console.log(conn.log + "2");
})
};
and here is my bassCtrl.js :
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
exports.get_user = function(req, resp) {
db.executeSql("select * from mst_user", function(data, err) {
console.log("in controller");
if (err) {
httpMsgs.show500(req, resp, err);
} else {
httpMsgs.sendJson(req, resp, data);
};
});
};
and here is my routes.js
var express = require('express');
var bassCtrl = require("../controllers/bassCtrl");
var httpMsgs = require("../core/httpMsgs");
var jwt = require('jsonwebtoken');
module.exports = function(app, express) {
var router = express();
router.route('/get_user').get(bassCtrl.get_user);
return router;
};
below is my HttpMsgs.js :
var settings = require("../settings");
exports.show500 = function(req, resp, err) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head><body>500: Internal Error. Details: " + err + "</body></html>");
} else {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Error occurred: " + err }));
}
resp.end();
}
exports.sendJson = function(req, resp, data) {
resp.writeHead(200, {"Content-Type":"application/json"});
if (data) {
resp.write(JSON.stringify(data));
}
resp.end();
}
exports.show405 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(405, "Method not supported", {"Content-Type":"text/html"});
resp.write("<html><head><title>405</title></head><body>405: Method not supported.</body></html>");
} else {
resp.writeHead(405, "Method not supported", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Method not supported"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(404, "Resource not found", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>404: Resource not found.</body></html>");
} else {
resp.writeHead(404, "Resource not found", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Resource not found"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>413: Request Entity Too Large.</body></html>");
} else {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Request Entity Too Large"}));
}
resp.end();
}
exports.send200 = function(req, resp) {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "success", code: 200}
));
resp.end();
}
exports.showHome = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(200, {"Content-Type":"text/html"});
resp.write("<html><head><title>200</title></head><body>Your server connected dude ! :)</body></html>");
} else {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "Your server connected dude ! :)"}
));
}
resp.end();
}
and here is my settings.js :
exports.dbConfig = {
user: "root",
password: "",
host: "localhost",
database: "zouk"
};
exports.httpMsgsFormat = "json";
when i trigger localhost:5000/get_user, it just loading till it timed out, and my console.log print this line console.log(connection.log + "2"); with undefined as the value. is there something i missing?
wait a minute, why my question rated minus?
You didn't execute your query in Db.js file, and your code don't call the callback too, that's why it run until timeout.
var connection = mysql.createConnection({
host : ***,
user : ***,
password : ***,
database : ***,
});
connection.connect();
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
//your callback go here.
// callback(rows);//pass whatever you need in.
});
connection.end();
Plus, your controller have no require for httpMsgs. I think it should have.
I am trying to make a url shortener app using express. I have 2 middle wares for routes /shorten/:url* and /:code respectively. Somehow when I make requests like /shorten/iamarshad.com (requests that are not formatted and will fail my validateUrl method), middleware handling that request gets executed sometimes twice and sometime thrice. Why is this happening ?
Code for route.js:
var express = require("express");
var router = express.Router();
var crypto = require("./crypto");
var styles = "<style>#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond');" +
"body{background: #fefefe; word-wrap: break-word;}" +
"p {font-size: 30px;color: #b33c66;font-family: 'Cormorant Garamond', monospace;text-align: center;" +
"margin-top: 40vh;font-weight: 500;word-spacing: 2px;}</style>";
function verifyUrl(req, res, next) {
console.log("/shorten middleware called");
req.params.url += req.params[0];
console.log(req.params.url);
if (validateUrl(req.params.url)) {
req.db.collection("counter")
.find({_id: "counter"})
.toArray(function (err, docs) {
if (err) console.error("Error occurred while getting COUNTER document:", err);
req.encodedId = crypto.encode(docs[0].count);
next();
});
}
else {
var elem = "<p>Please enter correct and formatted url!</p>";
res.send(styles + elem);
}
}
function incrementCounter(req, res, next) {
// increasing counter
req.db.collection("counter")
.update(
{
_id: "counter"
},
{
$inc : {
count : 1
}
}
);
next();
}
function insertUrlDocument(req, res, next) {
//inserting new url document
var obj = {original_url: req.params.url, _id: req.encodedId, entry_time: new Date().toUTCString()};
req.db.collection("urls")
.insert(obj, function(err, data) {
if(err) console.error("Error happened while adding new document:", err);
});
next();
}
function sendResponse(req, res) {
var elem = "<p>" + JSON.stringify({'original_url': req.params.url, 'short_url': 'https://shorten-that.herokuapp.com/' + req.encodedId}) + "</p>";
res.send(styles + elem);
}
function validateUrl(url) {
var format = /(http:\/\/|https:\/\/)[a-z0-9\-]+[.]\w+/;
return (format.test(url));
}
router.get("/:code", function(req, res) {
console.log("/:code middleware called with url", req.params.code);
var code = req.params.code.toString();
// searching short-url-id
req.db.collection("urls")
.find({_id: code})
.toArray(function(err, docs) {
if(err) console.error("Error occurred while searching urls:", err);
console.log(docs);
if(docs.length > 0)
res.redirect(docs[0]["original_url"]);
else {
var elem = "<p>Oops, wrong url requested!</p>";
res.send(styles + elem);
}
});
});
// better solution needed
router.get("/shorten/:url*", [verifyUrl, incrementCounter, insertUrlDocument, sendResponse]);
module.exports = router;
Code for server.js:
var express = require("express")
, mongo = require("mongodb").MongoClient
, port = process.env.PORT || 8080
, path = require("path")
, routes = require("./routes")
, favicon = require("serve-favicon");
var app = express();
app.use(favicon(path.join(__dirname, 'public','favicon.png')));
app.use(express.static(path.join(__dirname, "public")));
var url = 'mongodb://localhost:27017/url-shortener';
mongo.connect(url, function(err, db) {
if (err) console.error("Error occurred while connecting to db:", err);
console.log("successfully connected to db.");
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
});
app.listen(port, function() {
console.log("App running on", port);
});
im trying to update my mongodb using a new json object i got from the browser but the update method doesnt do anything (i also tried to use updateOne and it still didnt work).
my server code:
var express = require("express");
var path = require("path");
var url = require("url");
var app = express(); // express.createServer();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname));
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
var insertMsg, Collection;
var socketMap = {};
MongoClient.connect('mongodb://127.0.0.1:27017/EladGuy', function(err, db) {
if(err)
throw err;
Collection = db.collection('messages');
console.log("connected to DB");
insertMsg = function (saveJson) {
console.log("Start Saving...");
db.collection('messages').insertOne(saveJson);
console.log("Finish saving successfuly...");
};
removeMessages = function(msg, callback) {
db.collection('messages').deleteMany(
{ "name": msg },
function(err, results) {
console.log(results);
callback();
}
);
};
updateMessage = function(msg,callback) {
db.collection('messages').updateOne({"name":msg.name},{$set: msg},function(err, results) {
console.log(msg.name);
console.log(results);
callback();
});
};
});
app.get("/TestUpdate", function(request, response) {
var screenId = request.query.id;
console.log("Updating station number: " + screenId);
var newMsg = {
"screensId":[parseInt(screenId)],
"name":"msg6",
"text":["Won the lottary?","Want to invest your money?","Shulberg investment company","Your money is important to us!"],
"images":["http://thefilipinoexpat.com/wp-content/uploads/2015/11/04_investment.jpg"],
"template":"/html/templateA.html",
"msgTime":5000,
"timeFrame":[
{ "startDate" : [2016,0,1], "endDate" : [2016,11,31], "days" : [0,1,2,3,4,5,6], "startTime" : 6, "endTime" : 23},
{ "startDate" : [2016,0,1], "endDate" : [2016,11,31], "days" : [5], "startTime" : 13, "endTime" : 20}] }
insertMsg(newMsg);
if (socketMap[parseInt(screenId)] != undefined) {
socketMap[parseInt(screenId)].emit('messageUpdate', newMsg);
}
response.send("SUCCESS!");
});
app.get("/screen=:screenNum", function(request, response) {
response.sendFile(__dirname + '/station/station.html');
});
app.get("/html/:template", function(request, response) {
var template = request.params.template;
response.sendFile(__dirname + '/station/' + template);
});
app.get("/stationPreview=:screenNum", function(request, response) {
response.sendFile(__dirname + '/station/stationPreview.html');
});
app.get("/*", function(request, response) {
response.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('sendId', function(stationId) {
socketMap[parseInt(stationId)] = socket;
});
socket.on('getMessagesByScreen', function(screenId) {
res = [];
Collection.find({"screensId":{'$eq': parseInt(screenId)}}).toArray(function(err, docs) {
docs.forEach(function(doc) {
res.push(doc);
});
socket.emit('sendMessages', res);
});
});
socket.on('getAllMessages',function(unUsed) {
res = [];
Collection.find().toArray(function(err, docs) {
docs.forEach(function(doc) {
res.push(doc);
});
socket.emit('sendAllMessages', res);
});
});
socket.on('deleteMessage', function(msg) {
removeMessages(msg, function() {
socket.emit('DeleteSuccessed', null);
});
});
socket.on('getMessage', function(msg) {
Msg = [];
Collection.find({"name":{'$eq': msg}}).toArray(function(err, docs) {
docs.forEach(function(doc) {
Msg.push(doc);
});
socket.emit('sendMessage', Msg);
});
});
socket.on('getStations', function(unUsed) {
Collection.distinct("screensId", function(err, stationsArray) {
socket.emit('sendStations', stationsArray);
});
});
socket.on('EditMessage', function(update){
updateMessage(update,function(){
console.log("UPDATE SUCEES!!!");
});
});
});
server.listen(8080, function() {
console.log("Messages Application Express node js server listening on port %d...", this.address().port);
});
as you may see in my socket im using:"on('EditMessage')" when this happening the server activate the function:"updateMessage" which gets the update which is a json object just like the other ones stored in the mongodb.
my update should find the name of the message (which is uniq to each message) and update the message.
when i do so i get on console from the undifined and the the message "UPDATE SUCCESS" and when i check again i see that it didnt do anything.
I am creating a client management system and I am using a RESTful approach to create a dash board or sorts.
But, unfortunate I am getting an error in terminal when trying to start a node server that looks like this
/Users/taylormoore/Desktop/Fitness-app/server.js:11
app.get('/clients', client.findAll);
^
ReferenceError: client is not defined
at Object.<anonymous> (/Users/taylormoore/Desktop/Fitness-app/server.js:11:21)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
server.js looks like
var express = require('express');
clients = require('./routes/clients')
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.get('/clients', client.findAll);
app.get('/clients/:id', client.findById);
app.post('/clients', client.addclient);
app.put('/clients/:id', client.updateclient);
app.delete('/clients/:id', client.deleteclient);
app.listen(3000);
console.log('Listening on port 3000...');
Client.js looks like
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('clientdb', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'clientdb' database");
db.collection('clients', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'clients' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving client: ' + id);
db.collection('clients', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.findAll = function(req, res) {
db.collection('clients', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.addclient = function(req, res) {
var client = req.body;
console.log('Adding client: ' + JSON.stringify(client));
db.collection('clients', function(err, collection) {
collection.insert(client, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
exports.updateclient = function(req, res) {
var id = req.params.id;
var client = req.body;
console.log('Updating client: ' + id);
console.log(JSON.stringify(client));
db.collection('clients', function(err, collection) {
collection.update({'_id':new BSON.ObjectID(id)}, client, {safe:true}, function(err, result) {
if (err) {
console.log('Error updating client: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(client);
}
});
});
}
exports.deleteclient = function(req, res) {
var id = req.params.id;
console.log('Deleting client: ' + id);
db.collection('clients', function(err, collection) {
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred - ' + err});
} else {
console.log('' + result + ' document(s) deleted');
res.send(req.body);
}
});
});
}
/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {
var clients = [
{
name: "Bill",
age: "23",
email: "Bill#gmail.com",
phone: "233-229-7805",
description: "The aromas of fruit and spice...",
picture: "saint_cosme.jpg"
},
{
name: "Bill",
age: "23",
email: "Bill#gmail.com",
phone: "233-229-7805",
description: "The aromas of fruit and spice...",
picture: "lan_rioja.jpg"
}];
db.collection('clients', function(err, collection) {
collection.insert(clients, {safe:true}, function(err, result) {});
});
};
I am just getting into using the Stack and am not extremely familiar with how things are suppose to work. Please Help!