Update student
function update_student(req, student, next, res) {
console.log('----',student);
if (Object.keys(student).length > 0) {
var query = updateQuery('student', req, student, '_id');
var update_data = [];
Object.keys(student).forEach(function(key) {
update_data.push(student[key])
});
db.query(req, update_data).then(function(result) {
return res.send('Updated');
})
}
else {
return res.send('nothing to update');
}
};
Update query
function updateQuery(tablename, id, data, condition) {
var query = ['UPDATE'];
query.push(tablename)
query.push('SET');
var set = [];
Object.keys(data).forEach(function(key, i) {
if ((key == 'university_id') || (key == 'name') || (key == 'branch') || (key == 'age') || (key == 'email')) {
set.push('"' + key + '"' + ' = $' + (i + 1));
} else {
set.push(key + ' = $' + (i + 1));
}
});
query.push(set.join(', '));
query.push('WHERE ' + condition + ' = ' + id);
return query.join(' ');
}
What's wrong in the code? I am trying to write the update query in postgreSQL using node.js. I'm not able to update the student table using this query.
Related
if (fs.existsSync('tmp/cache.txt')) {
fs.readFile("tmp/cache.txt", function (err, data) {
if (data != "" || data != "[]") {
jdata = JSON.parse(data);
if (
jdata[jdata.length - 1].substring(4, 8) ==
new Date().getFullYear() + 543
) {
year = new Date().getFullYear() + 542;
console.log("yes this year");
}
jdata.forEach(function (value, i) {
if (
value.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
});
jdata.splice(countloveme);
}
});
}
my code is running but
code is finished before fs.readFile inside ifelse have finish
i don't how to add await in fs.readFile or anyway to this code is working
As written in the comments, it would be a better choice to use fs,readFileSync
And when you use Array.forEach() you are starting a new function that is running synchronously.
I've cleared your code maybe this can help you
if (fs.existsSync('tmp/cache.txt')) {
try {
const data = fs.readFileSync("tmp/cache.txt");
if (!data || data != "" || data != "[]")
throw new Error('tmp/cache.txt file is empty');
const jdata = JSON.parse(data);
// More clear to use variables in the if elses
const arg1 = jdata[jdata.length - 1].substring(4, 8)
const arg2 = new Date().getFullYear() + 543;
if (arg1 === arg2) {
// You don't use this date anywhere?
new Date().getFullYear() + 542;
console.log("yes this year");
}
for (let dataChunk of jdata) {
if (
dataChunk.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
}
jdata.splice(countloveme);
} catch (error) {
console.error(error.message);
}
}
Here is line 54, where I am getting the error:
if (docr.emails) {
And here is the rest of my original code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'abc', '$options': 'i' }
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
Try the following:
function findMeetings(db, meeting, callback) {
var host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, docr) {
var emails = [];
if (!err && docr && docr.emails) {
docr.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
...
I am using node js script to sync data(for multiple users) from GeoTab server APIs to my local db and using below code
var syncUsers = function () {
for (var i = 0; i < geotabUsers.length; i++) {
if (apiInstanse[geotabUsers[i].userId] == undefined)
{
apiInstanse[geotabUsers[i].userId] = new API(geotabUsers[i].apiUsername, geotabUsers[i].apiPassword, geotabUsers[i].apiDatabase, js_lang.GEOTAB_SERVER);
}
syncStatusData(apiInstanse[geotabUsers[i].userId], i, userInfo[geotabUsers[i].userId].statusDataFromVersion, geotabUsers[i].userId, userInfo[geotabUsers[i].userId].currentCompany, geotabUsers[i].apiUsername, geotabUsers[i].apiPassword, geotabUsers[i].apiDatabase);
}
var syncStatusData = function (api, i, fromVersion, userId, currentCompany, apiUsername, apiPassword, apiDatabase){
try {
api.call(js_lang.GEOTAB_GETFEED_METHOD, {
typeName: js_lang.GEOTAB_STATUS_DATA,
resultsLimit: js_lang.GEOTAB_API_LIMIT,
fromVersion: fromVersion
}, function (err, data) {
if (err) {
console.log('api Call Error:', userId);
console.log('apiUsername:', apiUsername);
console.log('apiPassword:', apiPassword);
console.log('apiDatabase:', apiDatabase);
console.log('Error', err);
apiInstanse[userId] = new API(apiUsername, apiPassword, apiDatabase, js_lang.GEOTAB_SERVER);
return;
}
var insertStatus = [];
var sql = "INSERT INTO " + js_lang.TABLE_STATUS_DATA + " (companyId,dateTime,deviceId ,diagnosticId,value,version,uniqueId,userId,unitOfMeasure ) VALUES ?";
//iterate data
if (data.data != undefined)
{
for (var key in data.data) {
if (diagnosticList[data.data[key].diagnostic.id] == undefined)
{
continue;
}
var thisDate = moment(new Date(data.data[key].dateTime));
var thisDayDate = thisDate.format("YYYY-MM-DD");
//prepare data to insert
var insertRow = [
currentCompany,
thisDate.format("YYYY-MM-DD HH:MM:ss"),
data.data[key].device.id,
data.data[key].diagnostic.id,
data.data[key].data,
data.data[key].version,
data.data[key].id,
userId,
diagnosticList[data.data[key].diagnostic.id].unitOfMeasure
];
insertStatus.push(insertRow);
var todayDate = moment(new Date());
var todayDayDate = todayDate.format("YYYY-MM-DD");
//send alert in case of current day data
if (todayDayDate == thisDayDate)
{
//send mails in case of high pressure
if (diagnosticList[data.data[key].diagnostic.id].unitOfMeasure == js_lang.GEOTAB_PRESSURE_UNIT_STR &&
data.data[key].data > js_lang.MAX_PRESSURE &&
alertTemplates[userId] != undefined)
{
console.log('alert time');
if (alertTemplates[userId] != undefined)
{
for (var templateIndex = 0; templateIndex < alertTemplates[userId].length; templateIndex++) {
var template = alertTemplates[userId][templateIndex];
var res = template.devices.split(",");
var index = FUNCTION_CLASS.contains.call(res, data.data[key].device.id)
if (index)
{
var emailSubject = 'High Pressure Alert';
if (userDevices[userId][data.data[key].device.id].name != undefined)
{
var emailText = 'Vehicle:' + userDevices[userId][data.data[key].device.id].name;
}
else
{
var emailText = '';
}
var toEmails = template.emails;
var emailHtml = 'Vehicle:' + userDevices[userId][data.data[key].device.id].name + '<br>' + diagnosticList[data.data[key].diagnostic.id].name + ' <br> value:' + data.data[key].data + ' ' + js_lang.GEOTAB_PRESSURE_UNIT_PA + '<br>\
' + js_lang.DATE_TIME + ':' + thisDate.format("YYYY-MM-DD HH:MM:ss");
//call mail function
sendEmail(toEmails, emailSubject, emailText, emailHtml);
}
}
}
}
}
}
}
if (insertStatus.length > 0)
{
connection.query(sql, [insertStatus], function (err) {
if (err)
throw err;
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET statusDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
});
}
else {
console.log('update user:', userId);
connection.query('UPDATE ' + js_lang.TABLE_USER + ' SET statusDataFromVersion = ? WHERE id = ?',
[data.toVersion, userId]);
}
if ((geotabUsers.length - 1) == i)
{
console.log('loop ended');
continueSync();
}
});
}
catch (e) {
continueSync();
}
}
var continueSync = function () {
setTimeout(function () {
connection.end();
geotabUsers = [];
userDevices = [];
diagnosticList = [];
userInfo = [];
alertTemplates = {};
eventEmitter.emit('getUsers');
}, 60000);
}
Its work fine for few iteration but getting random errors like
events.js:85
throw er; // Unhandled 'error' event
^
Error: Quit inactivity timeout
Or
events.js:85
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
I was getting this error while executing app on local, To remove problem I have used pm2 node module for process management.Now its working fine.
I am trying to make multiple http get requests in nodeJs. I need to continue getting records until there are no more available. I am having problems trying to do the iteration of a chunk of code. I had been reading about the async module but I am not understanding how to apply it. Please help.
Here is the New code 11/25/2014:
The step I want to repeat is the GetUrl(newBlock) is the step I want to repeat until there is no more blocks. I determine that there is no more blocks when the result.lenght of the request response is less than 5,000.
Is there a way of me getting this parameter pack from newBlock function and then stop the loop if I use the whilst async module?
// JS Script: GPSAPIClient
// Code Description: API client code to retrieve GPS data for customer with account number: 47631
// This script requires Node.Js environment installed with Request() and Node-crontab modules (through NPM).
// It will run (as a backend script) every minute and retrieve the GPS available.
//
// Author : Vanessa Torres, Professional Services
var request = require("request");
var fs = require('fs');
var async = require('async');
var crontab = require('node-crontab');
var csvFile = "";
var debug = false;
process.argv.forEach(function(val, idx, array) {
if (val.toLowerCase() === 'debug') {
debug = true;
console.log('\n\n\n******************DEBUG MODE ACTIVE(Do not run in prod)******************\n\n\n')
}
});
console.log('waiting to start running');
var jobId = crontab.scheduleJob('* * * * *', function() {
//Gettting system date and adding leading zeros when are single digits. I need this to build the get request with date filters.
var d = new Date();
var nday = d.getDate();
var nmonth = d.getMonth();
var nhour = d.getHours();
var nmin = d.getMinutes();
var nfullyear = d.getFullYear();
if (nday < 10) {
nday = '0' + nday;
};
//1 minute substraction except for when is zero (the value will negative).
if (nmin != 0) {
var nmin = nmin - 1;
};
if (nmin < 10) {
nmin = '0' + nmin;
};
// added because TLC Plumbing is 2 hours behind us. (MST)
nhour = nhour - 2;
if (nhour < 10) {
nhour = '0' + nhour;
};
var nmonth = nmonth + 1;
if (nmonth < 10) {
nmonth = '0' + nmonth;
};
var options = {
//url: 'https://credentials#api.comettracker.com/v1/gpsdata' + '?fromdate=' + nfullyear + '-' + nmonth + '-' + nday + 'T' + nhour + '%3a' + nmin + '%3a' + '00',
url: 'https://credentials#api.comettracker.com/v1/gpsdata?fromdate=2015-11-23T17%3a00%3a00&todate=2015-11-24T10%3a00%3a00',
method: 'GET',
rejectUnauthorized: !debug
};
function GetUrl(callback) {
return request(options, function(error, response, body) {
console.log('request for links');
if (error) throw new Error(error);
var result = JSON.parse(body)['links'];
var urlnext = result[2].href;
console.log('UrlNext: ' + urlnext);
console.log(result[2].rel);
//moreBlocks = newBlock(urlnext);
moreBlocks = callback(urlnext);
});
// request to get the next block of records (maximun 5,000)
};
// HTTP get request - 1st request
request(options, function(error, response, body) {
if (error) throw new Error(error);
var result = JSON.parse(body)['gps-recs'];
console.log(result.length);
//console.log(result);
//create .csv file if result.length is > = 1 (If we received GPS records)
if (result.length >= 1 && result.length < 5000) {
console.log('entered first if, result.length: ' + result.length);
buildCSV(result);
};
//add the subsequent request when result.length = 5000
if (result.length == 5000) {
console.log('entered second if, result.length: ' + result.length);
buildCSV(result);
console.log('I came back from buildCSV. result.length is : ' + result.length);
**GetUrl(newBlock)**;
//console.log('moreblocks back from newblock: ' + moreBlocks);
};
});
});
function newBlock(urlnext) {
console.log('URL passed to newBlock: ' + urlnext);
// option 2 - variables needed to built the url (like the first request)
var n = urlnext.length;
var rest = urlnext.substr(40, n);
console.log('Rest: ' + rest);
var options = {
url: 'https://credentials#api.comettracker.com/v1/gpsdata/' + rest,
method: 'GET',
rejectUnauthorized: !debug
};
request(options, function(error, response, body) {
console.log('nextblock request');
if (error) throw new Error(error);
var result = JSON.parse(body)['gps-recs'];
if (result.length == 0) {
//no records for filter
console.log('first if' + result.length);
moreBlocks = false;
};
if (result.length < 5000 && result.length > 0) {
//last block appends record and ends
appendCSV(result);
moreBlocks = false;
console.log('second if' + result.length);
};
if (result.length == 5000) {
//appends records but has to keep running
appendCSV(result);
console.log('third if- moreBlocks' + result.length);
};
console.log('moreBlocks: ' + moreBlocks);
});
};
function buildCSV(result) {
var csvFile = " ";
console.log('before csvFile: ' + csvFile);
//adding headers
csvFile = csvFile.concat('UserNumber' + ',' + 'UserTimeTag' + ',' + 'Latitude' + ',' + 'Longitude' + ',' + 'SpeedMph' + ',' + 'Heading' + ',' + 'Status' + '\r\n');
// loop runs result.length times
for (var i = 0; i < result.length; i++) {
csvFile = csvFile.concat(result[i].UserInfo.UserNumber + ',' + result[i].UserTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].SpeedMph + ',' + result[i].Heading + ',' + result[i].Status + '\r\n');
};
//console.log(csvFile);
fs.writeFile('file.csv', csvFile, function(err) {
if (err) throw err;
console.log('file saved');
});
};
//appending additional blocks
function appendCSV(result) {
var csvString = " ";
// loop runs result.length times
for (var i = 0; i < result.length; i++) {
csvString = csvString.concat(result[i].UserInfo.UserNumber + ',' + result[i].UserTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].SpeedMph + ',' + result[i].Heading + ',' + result[i].Status + '\r\n');
};
// console.log(csvString);
fs.appendFile('file.csv', csvString, function(err) {
if (err) throw err;
console.log('Data appended');
});
};
It is difficult to see if moreBlocks is in the same scope as the while. On the other hand, the while statement will start making calls indefinetilly until that flags changes, and that might be too late. You need to make sure you do each subsequent request at a time.
You could use async's ´whilst´ function:
var moreBlocks = true;
whilst(function(){
return moreBlocks === true;
},function(callback){
return request(options, function(err, res, body){
console.log('request for links');
if (err) throw new Error(err);
var result = JSON.parse(body)['links'];
var urlnext = result[2].href;
console.log('UrlNext: ' + urlnext);
console.log(result[2].rel);
//You NEED to make sure you update moreBlocks
moreBlocks = newBlock(urlnext);
// Go to next step.
return callback(res);
})
},{
//You are done!
//Call any function you'd like.
});
Check the docs here!
Edit, if newBlock is asynchronous:
var moreBlocks = true;
whilst(function(){
return moreBlocks === true;
},function(callback){
return request(options, function(err, res, body){
console.log('request for links');
if (err) throw new Error(err);
var result = JSON.parse(body)['links'];
var urlnext = result[2].href;
console.log('UrlNext: ' + urlnext);
console.log(result[2].rel);
//Now status has the info about moreBlocks.
return newBlock(urlnext, function(status){
moreBlocks = status;
// Go to next step.
return callback(res);
});
})
},{
//You are done!
//Call any function you'd like.
});
Somewhere on newBlock:
function newBlock(urlnext, callback) {
// some code..
return request(options, function(){
//here status decides if we are done.
return callback(status);
});
}
I am trying to create a new socket.io real time analytic connection. I have two types of users. Normal users and their drivers.
Here is the code for authorization
io.configure(function()
{
io.set('authorization', function(handshake, callback)
{
var userId = handshakeData.query.userId;
var type = handshakeData.query.type;
var accessKey = handshakeData.query.accessKey;
var query = "";
if(type = '')
query = 'SELECT * FROM users WHERE id = ' + userId + ' AND accessKey = ' + accessKey;
else
query = 'SELECT * FROM drivers WHERE id = ' + userId + ' AND accessKey = ' + accessKey;
db.query(query)
.on('result', function(data)
{
if(data)
{
if(type == '')
{
var index = users.indexOf(userId);
if (index != -1)
{
users.push(userId)
}
}
else
{
var index = drivers.indexOf(userId);
if (index != -1)
{
drivers.push(userId)
}
}
}
else
{
socket.emit('failedAuthentication', "Unable to authenticate");
}
})
.on('end', function(){
socket.emit('failedAuthentication', "Unable to authenticate");
})
});
});
For disconnection i have this
socket.on('disconnect', function()
{
});
i want to remove the very userId i added on disconnect. How would i do that. can i append anything to socket or what should i do?
If you're just trying to remove the userId from your users and drivers arrays, you can do this:
socket.on('disconnect', function() {
// remove userId from users and drivers arrays
var index;
index = users.indexOf(userId);
if (index !== -1) {
users.splice(index, 1);
}
index = drivers.indexOf(userId);
if (index !== -1) {
drivers.splice(index, 1);
}
});
Or, you can DRY it up a bit:
function removeItem(array, item) {
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
}
socket.on('disconnect', function() {
removeItem(users, userId);
removeItem(drivers, userId);
});
This code assumes that you put this in the same closure where the userId variable is present. If you are not doing that, then you will probably need to put the userId as a property on the socket object so that it is accessible when you need it. You don't show the larger context of how your code is organized or where this event handler is located so we can't make a more specific recommendation without seeing that.