Can't find data from database after set it? - javascript

I have a piece of code which adds data to the database, then a function which gets the added data ID from the database. Problem is that, I get an error it couldn't be found, but it is in the database. How could I solve the problem?
[2017-06-03 18:01:25.855] [DEBUG] [default] - TypeError: Cannot read
property 'id' of undefined
Here is how the function looks like
function getLastUser(hash, socket, user){
query('SELECT * FROM users WHERE hash='+pool.escape(hash)+'', function(err, row){
if(err){
logger.error('Failed getting user hash: ' + user.name);
logger.debug(err);
socket.emit('message', {
type: 'error',
error: "Failed getting user hash"
});
return;
}
return row[0].id;
});
}
Here the calling
getLastUser(hash, user, socket);

Related

TypeError: res.render is not a function

I am having an issue with nodejs' res.render, it's telling me its not a function. I've looked at other posts on stack overflow and they do not solve my issue.
Here's the issue....
My app has a controller, called auth.js
In it, it exports this function called updateDiscount
exports.updateDiscount = (req,res,next) =>{
const { discounts, email, filename, decide } = req.body;
switch(decide){
case "Approve":
approve(discounts,email,filename,decide, req, res);
break;
case "Deny":
deny(discounts,email,filename,decide, req, res);
break;
case "Defer":
defer(discounts,email,filename,decide, req, res);
break;
default:
return res.render('adminGrantPortal', {
message: 'You selected an option from the -- Approve/Deny/Defer -- menu which does not exist. Please contact your system administrator'
});
}
}
Next I have a WORKING METHOD called approve. So when the controller gets the approve message ( via variable decide in the switch ) It will approve a users discount in the DB. Again, this method is working...
approve = (discounts, email, filename, decide, req, res) =>{
// get discount based on name
mysqlConnection.query('SELECT id FROM discounts WHERE name=?', [discounts], async (error, results)=>{
if(error){
return res.render('adminGrantPortal',{
message: 'One or more fields either, do not exist in the database, or were filled out incorrectly during your last action.'
});
}
console.log('ayayay');
console.log(results[0]);
let discountID = results[0].id;
// Set staus in files table
mysqlConnection.query("UPDATE files SET status='approved' WHERE email=? AND filename=?", [email,filename], async (error,results)=>{
if(error){
return res.render('adminGrantPortal',{
message: 'Could not update users status, because it is not found in the database.'
});
}
// Add to discounts_users
mysqlConnection.query('INSERT INTO discounts_users (email,discountID) VALUES (?,?)',[email,discountID], async (error,results)=>{
if(error){
return res.render('adminGrantPortal', {
message: 'Cannot update the database, maybe this user already has this discount.'
});
}
return res.render('adminGrantPortal', {
message: 'Approved discount eligibility successfully.'
});
});
});
});
}
Now, I have a deny method, which means when the req.body.decide = 'deny' it goes here. This method gives me the error, specifically the line after the console.log('success');
deny = (discounts, email, filename, req, res) =>{
// Set staus in files table
mysqlConnection.query("UPDATE files SET status='denied' WHERE email=? AND filename=?", [email,filename], async (error,results)=>{
if(error){
console.log('error');
return res.render('adminGrantPortal',{
message: 'Could not update users status, because it is not found in the database.'
});
}
});
console.log('success');
return res.render('adminGrantPortal', {
message: 'Denied discount eligibility successfully.'
});
}
Why does it do this?
I've narrowed down some things that it is not.
I believe it is not that my 'results' object being returned from the mysqlconnection shares the same name as my res object, which would control the headers.
I believe it is not anything to do with my mysql, because I removed it to look like this...
deny = (discounts, email, filename, req, res) =>{
console.log('success');
return res.render('adminGrantPortal', {
message: 'Denied discount eligibility successfully.'
});
}
Yet I still get the same error....
TypeError: res.render is not a function
at deny (C:\Users\Andrew\Desktop\Project\racf\client\controllers\auth.js:187:16)
at exports.updateDiscount (C:\Users\Andrew\Desktop\Project\racf\client\controllers\auth.js:127:13)
at Layer.handle [as handle_request] (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\Andrew\Desktop\Project\racf\node_modules\express\lib\router\index.js:174:3)
Can anyone help me to figure out what I am doing wrong?
When calling the deny function, you are passing req as the 5th argument but you are trying to use it as res inside the function. Add decide to the deny function's argument list after filename.
deny = (discounts, email, filename, decide, req, res) => {
// ...
}

How to handle error in Angular Controller from MongoDB database update/delete in Express?

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?
I have the following route in Node/Express:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
//log the reason for the error
res.status(code || 500).json({
"error": message
});
}
app.delete("/polls/:id", auth, function(req, res) {
db.collection(POLLS_COLLECTION).deleteOne({
_id: new ObjectID(req.params.id), userID: req.user.id
//userID must match the req.user.id from Passport to make sure the poll belongs to the user
}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to delete poll");
} else {
res.status(204).end();
}
});
});
The following in an Angular JS controller:
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
alert("Error deleting poll");
console.log(response);
})
};
deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:
this.deletePoll = function(pollId){
var url = "/polls/" + pollId;
return $http.delete(url);
};
What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.
However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.
Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?
You can do like code below
Put this HTML code where you want to show error message :
<div style="color:red;">
{{error}}
</div>
In your angular js controller :
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
$scope.error="Any error message you like to show";
console.log(response);
})
};
If your API return an error. you can catch it like this :
Polls.deletePoll($routeParams.pollId).then(function(response) {
//SUCCESS CODE
}).catch(function(error) {
//NOTIFY ERROR
//NotifyService.display(error);
console.log(error);
});
thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:
if(err){
res.status(500).end();
}
if(result.deletedCount === 0){
res.status(404).end();
//error handling in Angular error callback
} else {
res.status(204).end();
//error handling in Angular success callback
}
});
});
this makes sure that not always a 204 is send whether or not the delete was successfull.

writing a query and return one value from a database in node js and mongoose

im writing a query in node js, my model of schema has 3 objects( userid, tokenid, mediaid), and i want to find the token id of a certain userid and use it in another function.
my code is as below:
app.get('/registeruser/:userid', function(req, res){
var name = req.params.userid;
user.findOne({userid: name},function(err, users1){
if(!users1){
res.send('Error 404, user not found');
return res.status(404).send();
}
else{
var query = user.find({tokenid: 1});
query.where({userid: name});
query.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});
user is the name of my model.
i run my code and i expect it to return the tokenid but it returns this: []
with these in my database:
userid: 'hgfj1234',
tokenid: 'juiodkdn12345678',
mediaid: ['med10', 'med11']
when i write userid: 'hgfj1234' it gives me this: [] but i want the real tokenid.
if anyone can help me i really appreciate it.
thanks in advance.
You don't need to do additional request to get record from mongodb.
That's enough to use findOne with complex attributes.
Try this:
app.get('/registeruser/:userid', function(req, res) {
var query = {
userid: req.params.userid,
tokenid: {$exists: true, $not: {$size: 0}}
};
user
.findOne(query)
.exec(function(err, User) {
if(err) { // error happen,
console.error(err); // log error
return res.status(500).send({
success: false,
message: 'System error'
}); // respond with 500 status and send json response with success false and message. return will stop execution to go down
}
if(!User) { // response from database was empty or null
return res.status(404).send({
success: false,
message: 'User not found'
}); // respond with 404 status and send json response with success false and message. return will stop execution to go down
}
res.send({
success: true,
tokenid: User.tokenid
}); // and at last everything is ok, we return json response with success and tokenid in response
});
});
attributes in query variable means to request mongodb to give us document with userid defined in request and that has tokenid that is defined and not is empty string (not size 0).
if You still did not getting desired result so check database for existence of necessary document.
If I understand your query right, you will reduce all find() calls to the tokenid with value 1. You will receive only any result, if the user has the token "1".
I suspect you wanted to code a projection, that is the second parameter on find():
var query = user.find({"userid": name});
query.select({"tokenid": 1})
.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});

Why is my query working on pgAdming but when I execute it from the server I get a query error (Error: Connection Terminated)?

I'm working on my Capstone project and it requires to store some telemetry data on a database. I'm using PostgreSQL 9.5 for the database and node for the server.
My problem is that when I try to send a query from the server I'm getting a query error [Error: Connection Terminated]. If I use JSON.stringify(err) I only see empty brackets as the result {}. What is interesting is that if I use pgAdmin client and execute the same query, the record is added successfully without any kind on error.
Here is the code I'm using in the server to send the query:
client.connect(function(err) {
if(err){
return console.error('could not connect to postgres', err);
}
//Checks if there is survey data to process
if(surveyFlag){
//Query to insert survey record
//Returns survey record's auto-generated id to use it when creating or updating the //telemetry record in the database
var query = 'INSERT INTO survey_response (perceived_risk, actual_risk) '+
'VALUES (' + telemetryRecord.survey.perceivedRisk +', ' +
telemetryRecord.survey.actualRisk +') ' +
'RETURNING survey_id';
client.query(query, function(err, result) {
console.log("Query: " + query);
if(err) {
console.log(err);
return console.error('error running survey query', err);
}
surveyID = result.rows[0].survey_id;
//Testing
console.log ("Survey response added with ID: " + surveyID);
});
//Close the connection
client.end();
});
The code client.end() is put at the same level of the code client.query(). Since client.query() is asynchronous, the client.end() gets called immediately after you start the query. By the time the query comes back the client has already ended which is causing the problem.
Try placing the client.end() code within the callback function of client.query().
client.query(query, function(err, result) {
console.log("Query: " + query);
if(err) {
console.log(err);
return console.error('error running survey query', err);
}
surveyID = result.rows[0].survey_id;
//Testing
console.log ("Survey response added with ID: " + surveyID);
//Close the connection
client.end();
});

How do I pass error messages from meteor server to client

I am using a meteor method to retrieve values from a client side function. I am using stripe api, it is working fine
However when there is a error in the stripe.charges.create function the error is not passed back to the client, which results in the stripeCheckout method sending the user to the complete template. I assume there is a way to take the errors in the Stripe.charges.create err.type response from stripes servers or the Stripe.customers.create function on the server side pass them to the client and let the user know the specific error as well as not sending them to the complete template using a if statement based on errors or Status of success from the stripe server which is passed to the meteor.
It's that connection from the error response from stripes 'Stripe.charges.createfunction to the meteor server and then passing it back to the client through thestripeCheckout` method.
Ok Hope I can get this solved. And any tips to approach this token creation, customer creation and charge in better practice, I am open to any suggestions.
Thanks!
Client JS
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
address_line1: addressValue1,
address_line2 : addressValue2,
address_city: cityValue,
address_state: provinceState,
address_country: country,
address_zip: zip,
name: firstName + lastName
}, stripeResponseHandler);
function stripeResponseHandler(status, response) {
if (response.error) {
alert(response.error.message);
}else{
// response contains id and card, which contains additional card details
var token = response.id;
Meteor.call('stripeCheckout',token, function (error, result) {
Router.go("/complete");
});
}
}
Server JS
Meteor.methods({
stripeCheckout: function (token) {
Stripe.customers.create({
source: token
}, function(err, customer) {
id = customer.id;
if(err){
throw new Meteor.Error("create-failed", err.message);
}else{
throw new Meteor.Error("create-failed", err.message);
}
Stripe.charges.create({
amount: 1000,
currency: 'usd',
customer: id
}, function (err, res) {
if(err){
throw new Meteor.Error("create-failed", err.message);
}else{
throw new Meteor.Error("create-failed", err.message);
}
});
});
}
});
UPDATE:
I added my current error detecting, I throw a error in all instances and I get this response in my console.
Exception in delivering result of invoking 'stripeCheckout': TypeError: Cannot read property 'error' of undefined
at http://localhost:3000/client/stripeClient.js?0eb126fd5e018d3cac3f8ec1505f32b7fdc97604:197:22
at Meteor.bindEnvironment [as _callback] (http://localhost:3000/packages/meteor.js?81e2f06cff198adaa81b3bc09fc4f3728b7370ec:977:22)
at _.extend._maybeInvokeCallback (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:3858:12)
at _.extend.receiveResult (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:3878:10)
at _.extend._livedata_result (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:4931:9)
at onMessage (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:3723:12)
at http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:2717:11
at Array.forEach (native)
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?0a80a8623e1b40b5df5a05582f288ddd586eaa18:156:11)
at _.extend._launchConnection.self.socket.onmessage (http://localhost:3000/packages/ddp.js?41b62dcceb3ce0de6ca79c6aed088cccde6a44d8:2716:11)
This is the Stripe POST /v1/customers response
{
error:{
message: "Your card was declined."
type: "card_error"
code: "card_declined"
}
}
Simply throw a Meteor.Error like this:
Meteor.methods({
stripeCheckout: function (token) {
Stripe.customers.create({
source: token
}, function(err, customer) {
id = customer.id;
Stripe.charges.create({
amount: 1000,
currency: 'usd',
customer: id
}, function (err, res) {
// first argument is error code, second is error details
throw new Meteor.Error("create-failed", err.message);
});
});
}
});
You will get the error you threw in the error argument of the method callback.
See the docs here: http://docs.meteor.com/#/full/meteor_error

Categories

Resources