Retrieve MySQL insert id in Meteor method - mysql

I am relatively new to Node and Meteor and am trying to retrieve the insert ID of a MySQL query using the numtal:mysql package. The trouble I run into is the query function running on the server and not returning to the client. I need the ID to return to the client so I can route the client to the newly created entry.
Client:
Template.new.events({
'click .button.submit' : function(){
Meteor.call('demoFunc', function(error, result){
console.log(result);
});
},
});
Server:
Meteor.methods({
demoFunc:function(){
//construct deal object
var newDeal = {
dealer_id : 1,
client_id : 1
};
//deal query
liveDb.db.query('INSERT INTO deal SET ?', newDeal, function(err, result){
return result.returnId;
});
}
});
If I could get the result.returnId in the demoFunc method to return to the client then I would be golden. If anyone's run into anything like this or worked around this, any help would be greatly appreciated.

The best place to ask that is at https://github.com/numtel/meteor-mysql/issues
This is a community packages and I highly recommend not to use it in production, only for learning/fun. You can also contribute to this repo by adding that feature that you want.
It is expect that Meteor will support MySQL soon. Meteor bought Fatomdb: http://techcrunch.com/2014/10/07/meteor-acquires-yc-alum-fathomdb-for-its-web-development-platform/

I've had the same issue and solved the problem with this package usefulio:sync-methods. You can see how the package works in Github.
This package automatically adds a callback function to every syncMethod defined in server side. So, you can just call this callback function from inside the server method, after the async results have been processed.
So, the steps are:
1) Install the package: meteor add usefulio:sync-methods
2) Declare your method as a syncMethod like this:
Meteor.syncMethods({
demoFunc:function(callback){
//construct deal object
var newDeal = { dealer_id : 1, client_id : 1 };
//deal query
liveDb.db.query('INSERT INTO deal SET ?', newDeal, function(err, result){
callback(undefined, result.returnId);
});
}
});
3) On the client side, you just call the method in the Meteor way:
Meteor.call('demoFunc', function(err, result){
...
});

Related

SQL result lengths and showing nothing when searched

I want my Discord bot to check if a user that joined exists in a MySQL table. However, when it sends the query, it's basically telling me that it doesn't exist even though it should.
This is my current code:
bot.on('guildMemberAdd', async (member) => {
console.log(member.id)
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`
let result = connection.query(query)
if(result.length > 0){
console.log("It works!")
}
})
Node is asynchronous, so here you try to console.log result before it has been populated...
You'll find more info in this here :
Node JS MySQL query function not returning result
How do I return callback of MySQL query and push to an array in Node.js?
Here is the code with a callback function. Try it, it should work:
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`
connection.query(query, function (err, result) {
if (!err) {
if (result.length > 0) {
console.log("It works!")
}
}
});
Explanation:
As BadSpencer has stated, the mysql driver is asynchronous, and based around callbacks.
Say you're planning on picking your friend up to go to a sporting event. You're not sure when they want you to come, so you call them on the phone and ask them. They think about it for a while, and then tell you a time. You got the information you requested, so you hang up. In programming terms, this would be an example of synchronous code (sometimes thought of as "normal" code in Node.js).
Put yourself back in the same situation. However, when you call your friend this time, they're very busy. You don't want to bother them so you ask them to call you later. You hang up, but now you wait. An hour later, they call you back and tell you the time. This is the thought process of asynchronous code.
There's a lot more that goes on behind the screen, but for simplicity's sake, I'm not going to bombard you with all that information in this answer.
Solutions:
You should pass a function to act as a callback which will use the returned data. Consider this example:
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`;
// Passing the callback function as the second parameter.
connection.query(query, (err, result) => {
if (err) return console.error(err);
if (result.length > 0) console.log('It works (it actually does).');
});
However, this callback-based nature can become a nightmare due to the scope of the result and subsequent flow of the code. After a few queries, your code can become messy. To prevent this, you can wrap the query in your own Promise (or use a Promise-based version of the mysql package, like promise-mysql) and await the calls.
Here's an example setup:
// Defining 'connection' as a parameter so
// you can export this function and use it
// anywhere.
function query(connection, sql) {
return new Promise((resolve, reject) => {
connection.query(sql, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
// Asynchronous context needed for 'await' (this needs to be within an async function).
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`;
let result = await query(connection, query)
.catch(console.error);

Nodejs passport setup confusion

I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.

how to create pagination using mysql and node js express web api note:im not using orm

Im trying to do pagination on mysql select * from student result here is my API once i fire the api again it returns the same reords returned on first call
i have done alot of research but most of the examples use mongodb not mysql
router.get('/getPlanPeriods', auth.verifyToken,(req, res)=> {
jwt.verify(req.token, secreteKey)
connection.query('SELECT * FROM student limit=?,?',[req.query.limit,oquery.query.offse] (err,rows,fields) =>
{
if(!err)
res.send(rows);
});
});

Connecting to RDS database from node.js

I am trying to learn node.js so that I can actually get started on working on my personal project. I have been trying to follow the examples in the book "Learning node.js" (by Marc Wandschneider). I, at this point, decided to forgo practicing his example, and go straight into using his code as framework for my practice code.
In my practice code, all I am trying to do is connect to my RDS database (no, I am not using Elastic Beanstalk, btw), and output contents of one of the tables. Seems simple enough, but when I whip up the code for it (based on the book), it seems to attempt connection, but get hung up in the process. This is my code:
var pool = require('generic-pool');
var async = require('async');
var mysql = require('mysql');
var host = "<database-name>.cu8hvhstcity.us-west-2.rds.amazonaws.com",
database = "<database-name>",
user = "<username>",
password = "<someLongPassword>";
var dbClient;
async.waterfall([
// 1. establish connection to database
function (callback) {
console.log("Connecting to database " + database + "...");
dbClient = mysql.createConnection({
host: host,
database: database,
user: user,
password: password,
port: 3306
});
dbClient.connect();
},
// 2. select all from a table (let's go for locations)
function (cb)
{
var query = "SELECT * FROM locations"
console.log("running query \"" + query + "\"...");
dbClient.query(query, cb);
},
function (rows, fields, callback)
{
console.log(fields);
for (var i = 0; i < rows.length; i++)
{
console.log(JSON.stringify(rows, null, '\t'));
}
}
], function (err, results) {
if (err)
{
console.log("An error occurred...");
console.log(err);
}
else
{
console.log("Everything successfully completed!");
}
dbClient.end();
})
This is better than first attempt, when I put a database member to the argument passed to mysql.createConnection(), and it complained that database was unknown. In neither case did either "An error occurred..." nor "Everything successfully completed!" output to the window.
Is there any async stuff going on that is resulting in some kind of non-terminating infinite loop or something? How do I fix this?
The book has an associated GitHub page
NOTE:
Neither my example nor the cited GitHub code make use of that pool variable, so it can simply be commented out. All you need to do to run this yourself is to say npm install async,npm install mysql (as well as creating a dummy RDS database to point to, that contains locations table) before copying, pasting, and running this code.
EDIT:
I fixed the issue with database. I realized that the name of the database used '_', not '-'. Same issue (code hangs) still persists...
I did the following:
In the second function in the array, I needed two parameters, not one.
I fixed thus:function(results, cb)
The third function simply needed to callback(null)

Get data from MySQL database and pass it to jade an access it using nodejs

I have started nodejs to make a simple chat application in it.
For this I want to access all users which are in mysql database.
My code is like:
JS
exports.authenticate = function(req, res) {
//connection.connect();
var sql="SELECT * from users where username='"+req.body.user+"' and password='"+req.body.pass+"' LIMIT 1";
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows);
var str="Hi, <b>"+rows[0].name+"</b> ("+rows[0].email+")";
sql="SELECT DISTINCT username,name from users ORDER BY name";
connection.query(sql, function(err, datarows, fields) {
if (err) throw err;
//res.send('Your data is: ', rows+' <br/> All Users are : ', datarows.length+"<a href='/'>Login</a>");
str+='<ul style="list-style:none;width:300px">';
for(var index=0;index<datarows.length;index++)
{
str+="<li><a href='javascript:;'>"+datarows[index].name+", "+datarows[index].email+"</a></li>";
}
str+='</ul>';console.log(str);
console.log(str)//gives ul
});
str+="<a href='/'>Login</a>";
res.send(str);//this not gives the ul of other users
});
}
The above code has problems that I wrote console.log(str)//gives ul this prints the whole string like Hi, <b>Rohan</b> ("rohan#xyz.com")<ul><li><a>Something</a></li>....</ul>. But res.send(str); sends only Hi, <b>Rohan</b> ("rohan#xyz.com")<a href='/'>Login</a>.
Why this is happening?
Is my str variable not global?
Can I use res.send() many times, if yes then how?
Can I use the above code with jade then what code should I write for this.
I found this answer How to pass data form mongodb (using Mongous module) into nodejs view (using temp engine jade)? related to my problem
app.get('/', function(req, res) {
mgs(dbColl).find(function(data){
res.render('yourview.jade', { data: data });
});
});
Then,How to access data in yourview.jade
I also want to know for which type of applications we should use nodejs ?
Thank in advance.
This is happening because Node is asynchronous. Your res.send(str) is executed immediately after calling your inner connection.query(), therefore the callback which adds more hasn't executed before the send.
No, your str variable is not global.
I do not believe so. If you want to write to the response before sending it, you can use res.write().
Yes you can use Jade instead of what you're doing now. Take a look at the Jade docs. They are full of examples of variables being used in jade. To summarize it for you though, you should be able to access a variable with #{variable}.
As for your last question, I'm really not sure what you're asking. You can use node for alot of stuff, from controlling quadcopters to web sites and services.