I am using a button to go to the delete route and I am passing to it a key to identify which team to delete. Instead of deleting just one team it deletes ALL teams when using the route. Any ideas?
Delete button:
button#teamDelete.btn.btn-danger.btn-mini(type="submit", value="Delete Team") Delete
script(type='text/javascript')
$('#teamDelete').live('click',function(){
var teamId = #{teamData.key};
$.post('/team/' + teamId, { _method : 'delete' }, function(response) {
console.log(response);
});
});
Team routes:
app.get('/team'/*, lim("Must be logged in to see teams")*/, getAllTeams, function(req, res){
util.log('Serving request for url [GET] ' + req.route.path);
// Pass it the list of all Teams
res.render('team', {'teamsList' : req.teamsList} );
});
/**
* POST /team
* Save new Team
*/
app.post('/team', function(req, res) {
util.log('Serving request for url [POST] ' + req.route.path);
// Output to console the contents of req.body
// console.log('body: ', req.body);
// console.log('body.teamForm: ', req.body.teamForm);
// console.log('body.teamForm.name: ', req.body.teamForm.name);
// console.log('body.teamForm.teamKey: ', req.body.teamForm.teamKey);
// Get data from teamForm
var teamForm = req.body.teamForm;
// Save team in teamForm as new Team
var name = teamForm.name;
var team = new Team();
team.name = name;
// Save new Team to datbase
team.save(function(err){
var message = '';
var retStatus = '';
// No error - Successful Save
if(!err){
util.log('Successfully created new team: ' + name);
message = 'Successfully created new team: ' + name;
retStatus = 'success';
}
// Error - Unsuccessful Save, show error
else {
util.log('Error while creating team: ' + name + ' error : ' + util.inspect(err));
if(err.code === 11000){
message = 'Team already exists';
}
retStatus = 'failure';
}
// Return whether the Save was successful
res.json({
'retStatus' : retStatus,
'message' : message
});
});
});
/**
* GET /team/:key
* Get Team details by key
*/
app.get('/team/:key', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
Team.findByKey(req.params.key, function(err, teamData){
if(!err && teamData){
teamData = teamData;
res.render('teamDetails', { 'teamData' : teamData } );
} else {
util.log('Error in fetching Team by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team by key ' + req.params.key
});
}
});
});
/**
* DEL /team/:key
* Delete Team by key
*/
app.del('/team/:key', function(req, res) {
util.log('Serving request for url [DEL] ' + req.route.path);
util.log(req.params.key);
Team.remove(req.params.key, function(err){
var message = '';
var retStatus = '';
if (!err) {
util.log('Successfully deleting Team with key: ' + req.params.key);
message = 'Successfully deleting Team with key: ' + req.params.key;
retStatus = 'Success';
} else {
util.log('Error deleting Team with key: ' + req.params.key + 'Error: ' + util.inspect(err));
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team with key ' + req.params.key
});
}
});
});
Well, you haven't indicated, but I presume Team is a mongoose model, in which case you are not properly specifying your conditions parameter, which must be an object of key/value criteria. Try:
Team.remove({key: req.params.key}, function (err) {});
http://mongoosejs.com/docs/api.html#model_Model.remove
Related
I've got into an issue. Postgres code(query) is not executed at all. I have to mention that the connection with the DB is correctly done.
I've tried to debug the code but I don't really know what's the problem
'use strict';
const config = require('../config');
const emailService = require('./email-service');
const pg = require('pg');
pg.defaults.ssl = true;
module.exports = function(phone_number, user_name, previous_job, years_of_experience, job_vacancy){
console.log('sending email');
let emailContent = 'A new job inquiry from ' + user_name + ' for the job: ' + job_vacancy +
'.<br> Previous job position: ' + previous_job + '.' +
'.<br> Years of experience: ' + years_of_experience + '.' +
'.<br> Phone number: ' + phone_number + '.';
emailService.sendEmail('New job application', emailContent);
try{
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if (err) {
return console.error('Error acquiring client', err.stack);
}
client
.query(
'INSERT into job_applications ' +
'(phone_number, user_name, previous_job, years_of_experience, job_vacancy) ' +
'VALUES($1, $2, $3, $4, $5) RETURNING id',
[phone_number, user_name, previous_job, years_of_experience, job_vacancy],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
});
});
}
catch(e){
console.log(e, 'error[][][]')
}
pool.end();
} ```
I fetch unread messages in a middle ware that triggers my function every five minutes. It is successfully completing the request but eventually It triggers and crashes my nodejs process. With an error of:
Error: This socket has been ended by the other party
I have tried adding all these catches and error handling but It seams it eventually times out my connection to my inbox? Am I not reconnecting on every request to access my inbox?
Here is my code (also I have tried with authTimeout: 3000 in the config before anyone suggests that is the issue):
imap: {
user: 'myemail#gmail.com',
password: 'myPW',
host: 'imap.gmail.com',
port: 993,
tls: true,
keepalive: true
}
imaps.connect(settings.emailConfig).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['UNSEEN'];//only grab unread messages in LTS email
var fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
markSeen: true//mark as read
};
return connection.search(searchCriteria, fetchOptions).then(function (messages) {
console.log('looking for unread messages')
if (messages.length > 0) {
console.log('unread messages to save')
console.log('looking at messages : ' + util.inspect(messages, { depth: null }))
var saveUnreadEmais = messages.map(function (item) {//resolve each promise of unread message
var all = _.find(item.parts, { "which": "" })
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
simpleParser(idHeader + all.body, (err, mail) => {
var BarCode = "";
var subject = mail.subject;
var to = mail.to.value[0].address;
var from = mail.from.value[0].address;
var text = mail.text;
if (mail.subject.includes('Barcode :')) {//if the message to the system includes BarCode in the subject line grab it
var split = mail.subject.split(':');
BarCode = split[1];
}
if (!subject) {
subject = "LTS Email Recieved - Barcode : " + BarCode;
}
if (!text) {
text = "LTS auto email"
}
var newrec = {};
newrec.MessageDate = new Date();
newrec.MessageFor = to;
newrec.MessageFrom = from;
newrec.Message = text;
newrec.MessageAbout = BarCode;
newrec.MessageSubject = subject;
newrec.MessageStatusCode = 1;//1 sent, 2 read, 3 saved, -1 deleted
//console.log('saving message with details of : ' + util.inspect(newrec, { depth: null }))
return db.knex('dbo.PersonnelMessages').insert(newrec).then((data) => {
return "sent";
});
});
});
return Promise.all(saveUnreadEmais).then(() => {
//do anything you want after saving all unred emails to our db.
}).catch((err) => { console.log("error : " + err) })
}
else {
console.log('no new emails')
}
}).catch((err) => { console.log("error : " + err) })
}).catch((err) => { console.log("opening inbox error : " + err) })
}).then(function () {
console.log('In the INBOX');
}).catch(function (e) {
console.log('error : ' + e);
});
I am totally new on using JWT and tokens; I just tried to do this:
console.log("logged " + data);
//prints { _id: 5a82ee98e918b22e83d6c3e0,
//username: 'test2',
//name: 'test',
//surname: '2',
//password: '...'
//[etc]
//}
console.log("logged _id " + data._id);
//prints 5a82ee98e918b22e83d6c3e0
var token = jwt.sign(data._id, secret, {
expiresIn: "24h" // expires in 24 hours
});
console.log("saved token " + token);
//prints the token in style eyJhbGciOi[...].eyJfYnNvbn[...].usoLRz-[...]
console.log("decoded: " + JSON.stringify( jwt.decode(token) ) )
//prints the token in this way:
//{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[90,130,238,152,233,24,178,46,131,214,195,224]},"iat":1519502719,"exp":1519589119}
why it does not prints the id number in plain text?
how can i get the id number i put in the token?
UPDATE:
I am in a login function; data is the answer after login, and it contains the user logged in; i have
var login = function(req, res) {
passport.authenticate('local', function(err, data, info) {
if (err) { console.log(err);
}
console.log("data in auth " + data);
if (!data) {
return res.status(404);
}
req.logIn(data, function(err) {
if (err) {
console.log("err " + err);
}
console.log("logged " + data);
console.log("logged _id " + data._id);
var token = jwt.sign[continues on top]
[...]
}
You are not decoding your token correctly
let decodedData = JWT.decode(token,secret);
console.log(decodedData._id);
No need to stringify your data. It will work fine. If you get any error, contact me anytime.
Solved.
Problem was that i put in the token data._id directly as string; as this link says, token payload must be built this way:
{
"_id" : data._id
}
so I do NOT have to do this:
console.log("logged _id " + data._id);
//WRONG
var token = jwt.sign( data._id, secret, {
expiresIn: "24h"
});
but I do have to do THIS WAY:
console.log("logged _id " + data._id);
var myId = {
"_id" : data._id
}
var token = jwt.sign( myId, secret, {
expiresIn: "24h"
});
so now if I use
let decodeddata = jwt.decode(token,secret);
console.log("decoded: " + JSON.stringify(decodeddata,null,4) )
then THIS WORKS.
Thanks to all for helping me finding the issue!
Node.js 6.10
Process is as follows...
1) Dropped an XML file into an S3 bucket.
2) Triggered a lambda,
3) Called a step function, which calls another lambda
4) This lambda captures the XML from the bucket with
var s3Bucket = new aws.S3( { params: {Bucket: 'bucketName'} } );
var xmlFile = s3Bucket.getObject('fileName.xml');
5) send an email with the contents of the XML as a string
let index = function index(event, context, callback) {
var fileName = event.fileName;
var bucketName = event.bucketName;
var todaysDate = event.todaysDate;
var eParams = {
Destination: {
ToAddresses: ["emailAddress"]
},
Message: {
Body: {
//Text: { Data: 'file: ' + fileName + ' bucketName: ' + bucketName + ' todaysDate: ' + todaysDate}
Text: { Data: 'file: ' + JSON.stringify(xmlFile)}
},
Subject: {
Data: "Email Subject!!!"
}
},
Source: "emailAddress"
};
console.log('===SENDING EMAIL===');
var email = ses.sendEmail(eParams, function(err, data){
if(err) console.log(err);
else {
console.log("===EMAIL SENT===");
console.log(data);
console.log("EMAIL CODE END");
console.log('EMAIL: ', email);
context.succeed(event);
}
});
};
module.exports.init = (event, context, callback) => {
};
exports.handler = index;
I know the sending an email works because if I uncomment the line
Text: { Data: 'fileName: ' + fileName + ' bucketName: ' + bucketName + ' todaysDate: ' + todaysDate}
and comment out Text: { Data: 'file: ' + JSON.stringify(xmlFile)}
it sends the email with the correct filename, bucketName, and date
So when I try to include Text: { Data: 'file: ' + JSON.stringify(xmlFile)}
the logs show the error
ypeError: Converting circular structure to JSON at Object.stringify (native) at index (/var/task/index.js:39:51)
UPDATE
Thanks #Michael & #Khand for the replies. I have tried what you suggested
var params = {
Bucket: "bucketName",
Key: "fileName.xml"
};
s3.getObject(params, function(err, data)
{
if (err)
{
console.log(err, err.stack);
}// an error occurred
else
{
console.log("Returned data object " + data); // successful response
console.log("Returned xml " + data.body);
}
console is returning
Returned data object [object Object]
Returned xml undefined
and yes the bucket does contain the named file. The [object, object] is populated but the body tag is undefined
I am trying to save a match between 2 teams, I am passing the 2 teams through a drop down list.
When I use util.log to output the homeTeam to the console when INSIDE the Team.findByKey method it works successfully and here is the output:
3 Mar 19:52:33 - { name: 'Liverpool',
_id: 51312074bb176ba624000007,
__v: 0,
key: 1362174068837 }
But as soon as I try to do this outside of this method I get the following output which means that when I try to save this as a match, the hometeam appears as just undefined rather than the id of the hometeam:
3 Mar 19:54:09 - [object Object]
My problem is that I am eventually wanting to save both a home team and an away team to the same match in one save. The code for saving a match works when inside the Team.findByKey method which is as follows:
app.get('/save/matchTest', function(req, res) {
var key = 1362174006191; // Man Utd 51312036bb176ba624000001
Team.findByKey(key, function(err, team) {
util.log(team);
if(err) {
util.log("Error occured");
}
if(!team) {
util.log("The team does not exist");
}
var match = new Match({
hometeam: team._id
});
match.save(function(err) {
if(err) {
util.log('Error while saving Match: ' + util.inspect(err));
res.send("An error occured whilst saving the match");
} else {
res.send("Saved the match");
}
});
});
});
But what I want to do is to be able to save a match with the following
var match = new Match({
hometeam: homeTeam._id,
awayteam: awayTeam._id
});
Does anyone have any ideas?
Here is the relevant code:
JavaScript
submitMatch = function(){
var homeId = $("#homeTeamList").val();
var awayId = $("#awayTeamList").val();
//alert("home: " + homeId + " away: " + awayId);
// Frontend sends the data
var matchForm = {
homeKey : $('#homeTeamList').val(),
awayKey : $('#awayTeamList').val()
};
// Basic validation
$.post('/save/match', {'matchForm' : matchForm}, function(response) {
console.log(response);
});
};
/save/match
app.post('/save/match', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
// Output to console to test what is being passed to Save Match
// Entire body passed to console
//console.log('body: ', req.body);
// Entire matchForm from body
//console.log('matchForm: ', req.body.matchForm);
// Home Key from matchForm
//console.log('homeKey: ', req.body.matchForm.homeKey);
// Away Key from matchForm
//console.log('awayKey: ', req.body.matchForm.awayKey);
// Get data from match Form
var matchForm = req.body.matchForm;
// Check if a match with 2 teams has been submitted
if(matchForm.homeKey === '' || matchForm.homeKey === undefined ||
matchForm.awayKey === '' || matchForm.awayKey === undefined){
// Not a valid match
util.log('Not valid match');
} else {
var homeId = matchForm.homeKey;
var awayId = matchForm.awayKey;
var homeTeam = Team.findByKey(homeId, function(err, homeTeam) {
util.log(homeTeam);
if(err) {
util.log("Error occured");
}
if(!homeTeam) {
util.log("The home team does not exist");
}
});
var match = new Match({
hometeam: homeTeam._id
});
//util.log(match);
}
});
In /save/match you're using the value of homeTeam in the Match constructor before it's been set by the callback. You need to create the Match inside both the home and away team findByKey callbacks like this:
Team.findByKey(homeId, function(err, homeTeam) {
util.log(homeTeam);
if(err) {
return util.log("Error occured");
}
if(!homeTeam) {
return util.log("The home team does not exist");
}
Team.findByKey(awayId, function(err, awayTeam) {
util.log(awayTeam);
if(err) {
return util.log("Error occured");
}
if(!awayTeam) {
return util.log("The away team does not exist");
}
var match = new Match({
hometeam: homeTeam._id,
awayteam: awayTeam._id
});
});
});
To look up the home and away teams in parallel while still keeping your code organized, you'll want to look at using a flow control library like async.