Assignments done in pool.connect - javascript

What does it do?
In the documentation, I do not understand the answer.
I'm not using it correctly, I get a query error from the database
pool.connect(function (err, client, done) {
if (err) console.log("connect " + err.toString());
else
client.query('SELECT id, "idName", "idContact", "idExperience",
"idSkill", "dateAdded", "dateColloquy"' +
'FROM public."applicant ";', function (err, result) {
if (err) {
console.log("query " + err.toString());
}
else {
console.log(result.rows);
//module.exports.res = result.rows;
}
done();
});
});

Now there are many errors, the error you are getting from the database (sad that you don't share it with us) should be the "dateColloquy"FROM part. Now once you fixed that and inserted a space before FROM, you'll notice that all your fields are not included as data, but exactly as what you wrote - idName (literally the string), ... for every field but id the same.
Use backticks (```) (or nothing at all) for column names, not " nor '.
The next error you'll experience will be that you are trying to
module.exports.res = result.rows;
You can't export asynchronous retrieved data like that.

Related

ER_PARSE_ERROR node.js and mysql issue (INSERT INTO)

I want to do a simple insert with Node.js while I am using socket.io with node.js and MySQL. Don't know why, but I am geting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''markos'' at line 1
My code:
When I try this, I get the above error.
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ?";
con.query(sql, question, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
if I try this simple code, everything works fine:
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ('John')";
con.query(sql, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
The question parameter always has a string.
You're missing the parentheses around the values:
let sql = "INSERT INTO nodeJs (name) VALUES (?)";
// Here ------------------------------------^-^

appendFile() runs before readFile() even though appendFile() is chronologically after the readFile()

I am trying to write code that reads a file, counts the lines in it, and then adds another line with the line's number in the beginning. Like an index, basically. The problem is that the fs.appendFile() starts running before fs.readFile() is finished, but I am not sure as to why. Is there something I am doing wrong?
My code:
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
lines = data.split(/\r\n|\r|\n/).length - 1;
console.log("Im supposed to run first");
});
console.log("Im supposed to run second");
fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
if (err) throw err;
console.log('List updated!');
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
// Converting Raw Buffer dto text
// data using tostring function.
message.channel.send('List was updated successfully! New list: \n' + data.toString());
console.log(data);
});
});
My output:
Im supposed to run second
List updated!
Im supposed to run first
[0]first item
Currently, you are using readFile and appendFile. Both of these functions are asynchronous and will run at the same time, returning whenever they complete.
If you'd like to run these synchronously, you can use the fs.readFileSync and fs.appendFileSync methods to synchronously read and append to the files.
Therefore, with something like the following:
const readFileData = fs.readFileSync("list.txt");
fs.appendFileSync('list.txt', '[' + lines + ']' + item + '\n');
The first line of code will run, then the second line of code.
The functions you are using are asynchronous, so the response of the second function can be received before the response of the first one.
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
lines = data.split(/\r\n|\r|\n/).length - 1;
console.log("Im supposed to run first");
appendFile(lines);
});
let appendFile = (lines)=> {
fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
console.log("Im supposed to run second");
if (err) throw err;
console.log('List updated!');
fs.readFile('list.txt', 'utf-8', (err, data) => {
if (err) throw err;
// Converting Raw Buffer dto text
// data using tostring function.
message.channel.send('List was updated successfully! New list: \n' + data.toString());
console.log(data);
});
});
}

Fetching data from mongo using key in server js

i am accepting username and phone from the front end and now i need to send phone to mongodb and based on that phone i need to get the details of a matching student's detail.Please help me to achieve this.
this is my server code:
server.post('/phone',urlencodedParser,function(req,res){
var resp={
Username : req.body.username,
phn:req.body.password
}
databaseInterface.studentDetail(resp.phn);
res.json(resp.phn);
console.log(resp);
res.send('username :' + req.body.username + 'passwrd:' + req.body.password);
})
this is my mongoDB code:
function studentDetail(phn){
User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
if (err) return phn(err);
return phn(null, studentcollection2);
}).select('-__v');
}
The callback that you are using has some problem.
function studentDetail(phn,callback){
User.findOne({'Father.PhoneNo':phn},function(err,studentcollection2){
if (err) return callback(err);
return callback(null, studentcollection2);
}).select('-__v');
}
for ur response,
databaseInterface.studentDetail(resp.phn, function(err, val){
if(err) res.send('ERROR!');
else res.send('Response');
});
Not Tested!
FindOne will return a promise. You need to wait for it to be fulfilled before returning your json.
To achieve that, you need to do the following:
databaseInterface.studentDetail(resp.phn).then((data,error) => {
res.json({response:data});
});
Your query seems wrong too.
function studentDetail(phone) {
return [yourQuery].exec()
}
I believe that's it

azure custom apis: performing database transaction returns a timeout

On a azure custom api, I'm attempting to perform bulk insert operation to three tables utilising database transctions.Then I'm facing this error on the console.
The request 'POST /api/saveinvite' has timed out. This could be caused by a script that fails to write to the response, or otherwise fails to return from an asynchronous call in a timely manner.
exports.post = function (request, response) {
console.log("save invite executed!!");
var jsonfriendcircle = request.body.jsonfriendcircle;
var jsoninviteelist = request.body.jsoninviteelist;
var jsoninviteefriendcirclelist = request.body.jsoninviteefriendcirclelist;
console.log("Circle is :" + jsonfriendcircle);
console.log("Inviteelist is :" + jsoninviteelist);
console.log("Inviteefriendcirclelist is :" + jsoninviteefriendcirclelist);
var parsedjsfrcircle = JSON.parse(jsonfriendcircle);
var mssql = request.service.mssql;
console.log("mssql obj :" + mssql);
mssql.open({
success: function (connection) {
console.log("connection to db success");
console.log("circle id: " + parsedjsfrcircle["id"]);
console.log("circle name :" + parsedjsfrcircle["circle_name"]);
var sqlst1 = 'insert into friendcircle (id,circle_name)values(?,?)';
connection.query(sqlst1, [parsedjsfrcircle["id"], parsedjsfrcircle["circle_name"]], function (err, results) {
if (err) {
console.log("Error:" + err);
connection.rollback();
response.send(statusCodes.Error, { message: '' });
connection.close();
return;
} else {
// connection.commit();
// connection.close();
}
});
}
, error: function (err) {
console.log("Unable to connect to DB :" + err);
response.send(statusCodes.Error, { message: err });
}
});
};
It doesn't look like your trying to do too much. Inserting a few hundred rows should come back before the timeout.
You'll get a timeout if there is permissions issues with the Mobile Services user on the database table and your transaction and custom error handling may be hiding that. Ensure you've run a
GRANT SELECT, INSERT, UPDATE ON OBJECT::[dbo].[Invitee_FriendCircle] TO [Created_MobileServicesLogin_User]
--For whatever name was created when you made the app (not the name you entered when you created the app, but the wacky one that mobile services made)
Some things to try:
Ensure the tables you are inserting to are indexed for the type of insert you're doing. If it's a huge table and indexing is an issue, let the mobile api insert to a small temp table and then run an asynch job with sp_start_job to update the main table with the temp table. That way you are not waiting while the table does the update.
Write stored procedures in the database that contain the inserts and pass the variables into them instead of writing the INSERT query here. Inside the sproc you can also do BULK INSERT if you really are passing a lot of values and need to do it quick.
Modify the ConnectionTimeout property in the connection string to your database.
You can modify the request.service.config.sqlConnectionString.
Try stripping it down to find the problem. Remove the transaction and just try doing it without the transaction and custom error handlers, on just one table at a time. Try
exports.post = function(request, response) {
var jsonfriendcircle=request.body.jsonfriendcircle;
var jsoninviteelist=request.body.jsoninviteelist;
var jsoninviteefriendcirclelist=request.body.jsoninviteefriendcirclelist;
var mssql=request.service.mssql;
var sqlst1='insert into FriendCircle (id,circle_name)values(?,?)' ;
mssql.query(sqlst1,[jsonfriendcircle.id,jsonfriendcircle.circle_name], {
success: function(results) {
response.send(statusCodes.OK, { message : 'success' });
},
error: function(err) {
console.log("error is: " + err);
}
});
};
Try them one at a time to see if anything fails, and if it does, check the LOGS on the Azure portal to see if it was a permission issue.
Good Luck!
Probably a transaction timeout after 30 seconds?
In SQL What is the default max transaction timeout
Try to rewrite the insert into multiple smaller transactions

node-mssql insert returning undefined recordset

Select statements are working fine, but whenever I try an insert or update the recordset and affected values are undefined. The insert/update works in the DB, I just can't read the returned values.
var sql = require('mssql');
var config = {...};
sql.connect(config).then(function() {
new sql.Request().query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset, affected) {
console.log('Recordset: ' + recordset);
console.log('Affected: ' + affected);
}).catch(function(err) {
console.log('Request error: ' + err);
});
}).catch(function(err) {
if (err) {
console.log('SQL Connection Error: ' + err);
}
});
The output to console is:
Recordset: undefined
Affected: undefined
I feel like I must be missing something really simple here.
As mentioned in the comments, INSERT statement doesn't return a recordset so recordset is undefined. Please see this section of the docs to learn more about how to get number of affected rows.
The problem with your code is you're expecting affected as a second argument from the promise, but promises does only support one argument. Because of that you must access number of affected rows this way:
var sql = require('mssql');
var config = {...};
sql.connect(config).then(function() {
var request = new sql.Request();
request.query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset) {
console.log('Recordset: ' + recordset);
console.log('Affected: ' + request.rowsAffected);
}).catch(function(err) {
console.log('Request error: ' + err);
});
}).catch(function(err) {
if (err) {
console.log('SQL Connection Error: ' + err);
}
});
If you want id to be output parameter
const sql = require("mssql/msnodesqlv8");
const pool = new sql.ConnectionPool(dbConfig);`
const poolConnect = pool.connect();
let query = `INSERT INTO <table>(fields) VALUES(values);SELECT #id = SCOPE_IDENTITY()`
await poolConnect;
pool.request()
.output("id", sql.Int)
.query(query).then((err, result) => {
console.log(result.output.id)
}).catch(err => {
console.log(err)
})`

Categories

Resources