I am using sequelize in my project. I am using the following format to get the results. But each row in the result is returned as textRow. Is it ok if I can directly access using the index or Do I need to convert textrow?
Need your suggestions.
const testQuery = await sequelizeConn.query(`select * from users where user_name = '${reqParams.userName}'`, {
raw: true
})
if(testQuery && testQuery.length > 0 && testQuery[0].length > 0){
}
You need to remove raw:true because already it's working like raw query and try promise instead of async/await.
sequelize.query(`select * from users where user_name = ${reqParams.userName}`, {model: users})
.then(function(result) {
if(result && result.length > 0 && result[0].length > 0){
console.log(result);
}
}).catch(error=>{
console.log(error);
});
Related
I need to get user information and use it in all file but when i save it to array or session array - it show undefined.
connection.query('SELECT * FROM users WHERE username = ? OR email = ? AND password = ?', [login, login, password], function (err, results) {
if (results.length > 0) {
req.session.username = results[0].username;
req.session.email = results[0].email;
req.session.password = results[0].password;
req.session.premium = results[0].premium;
req.session.created_at = results[0].created_at;
} else {
console.log("Error!");
}
});
The arrays and sessions are always undefined...
req is a function variable/public variable I assume. connection.query is asynchronous. Callbacks are always asynchronous, and every REST API is.
Asynchronous basically allows the function callbacks to run together with the next lines of code.
The reason why req isn't being returned any value is because the req's value gets printed out first before it's actually being assigned within the function.
If you would like to add everything to req, either do sth like:
someFunctionYouHaveCreated: (req,res,type) => {
connection.query('SELECT * FROM users WHERE username = ? OR email = ? AND password = ?', [login, login, password], function (err, results) {
if (results.length > 0) {
req.session.username = results[0].username;
req.session.email = results[0].email;
req.session.password = results[0].password;
req.session.premium = results[0].premium;
req.session.created_at = results[0].created_at;
} else {
console.log("Error!");
}
DoSomething(req);
});
}
DoSomething: (req) => {
//Do something
}
Or, create a promise, and run the function based on promise. Use promise.all to assign value: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all, but I don't think you need such level of complexity.
Below function I copy it from surveyjs-nodejs repository and looking to achieve this similar into mysql.
function getObjectFromStorage(tableName, callback) {
db.any("SELECT * FROM " + tableName).then(function(result) {
var objects = {};
(result || []).forEach(function(item) {
objects[item.id] = item;
});
callback(objects);
});
}
getObjectFromStorage("surveys", function(objects) {
if (Object.keys(objects).length > 0) {
callback(objects);
} else {
callback(surveys);
}
});
how this .any works?
db
.one("INSERT INTO surveys (name, json) VALUES($1, $2) RETURNING *", [
name,
"{}"
])
.then(callback);
and how this RETURNING * use in mysql?
Thanks
Below generate primary key auto-incremented but is there any way to assign or generate group id to those record which creates in one particular bulk using sequelize with MySQL.
or there is any way in mysql
here is my code
Model.bulkCreate(data,{individualHooks: true})
.then(function(result) {
console.log(result)
})
.catch(function(error){
console.log(error);
})
I did something like this,
first, I add the field with name groupId and then get groupid on every insertion and append with request bod.got time now so posting now :) might help some one else
tasks.max('groupId').then(function (maxid) {
var newbody = [];
for (var i = 0; i < req.body.length; i++) {
body.groupId = maxid + 1;
newbody.push(body);
}
tasks.bulkCreate(newbody, {individualHooks: true}).then(function (taskvalues) {
res.status(200).json(taskvalues);
}).catch(function (err) {
res.status(500).json(err);
})
I'm trying to extract specific document fields from a mongodb collection (v 3.0.8 at MongoLab). The returned documents must fall within a date range. My goal is to extract specific fields from these documents. My nodejs code,
var query = {}, operator1 = {}, operator2 = {}, operator3 = {} ;
operator1.$gte = +startDate;
operator2.$lte = +endDate;
operator3.$ne = 'move';
query['xid'] = 1; // Problem here?
query['date'] = Object.assign(operator1, operator2);
query['type'] = operator3;
console.log(query);
MongoClient.connect(connection, function(err, db) {
if(err){
res.send(err);
} else {
db.collection('jbone')
.find(query)
.toArray(function(err, result){
console.log(err);
res.json(result);
});
};
});
If I opt to return all fields in the date range, the query works fine. If I select only field xid I get no results. My query object looks sensible according to the docs. console.log(err) gives:
{ xid: 1,
date: { '$gte': 20160101, '$lte': 20160107 },
type: { '$ne': 'move' } }
null
null is the err.
Can anyone help me understand what I'm doing wrong?
Or point me to another similar SO questions with an answer?
Thanks
To select the specific field could be done as below
.find(
{date: { '$gte': 20160101, '$lte': 20160107 }, type: { '$ne': 'move' }},
{ xid: 1} )
Sample codes as following.
query['date'] = Object.assign(operator1, operator2);
query['type'] = operator3;
db.collection('jbone')
.find(query, {xid: 1})
.toArray(function(err, result){
console.log(err);
res.json(result);
});
When i type the username which is there in Table "fun" i am not facing any error but when i type wrong name that is the name which is not there in the table am facing error this is the error and code is attached below.
app.post('/Fu',function(req,res,next){
var username = req.body.uname;
var password = req.body.pwd;
con.query('SELECT name FROM fun WHERE name = "' + username +'" ',function(err, result,fields) {
var w = result[0].name;
if( username == w ){
console.log("login successful");
}
else{
console.log("login not successful");
}
}
});
res.send("success1");
});
can someone please help with the error.
This error is probably related to the fact that, when username is not present in the table, result will be set to and empty array []. That means that it has no elements at all, so result[0] is undefined.
Make sure to check for that before trying to get result[0].name.
Also, I would suggest you a few things:
1) Add error checking before anything else;
2) You do not need to check if the name is equal to the result. The query you wrote will only return entries that already match that requirement;
3) Send the responses inside the callback function, otherwise, the user will get the "success1" answer before the query has even finished executing.
Here follows the resulting code:
app.post('/Fu',function(req, res, next){
var username = req.body.uname;
var password = req.body.pwd;
con.query('SELECT name FROM fun WHERE name = "' + username +'"', function(err, result,fields) {
if (err) {
response.sendStatus(500);
return;
}
if (result.lenght > 0) {
res.send('Login was successful');
} else {
res.send('Login was not successful');
}
});
});
Your problem is here:
var w = result[0].name;
Because the result set at [0] doesn't exist (query came back with nothing). you are trying to get the name value from something that is undefined.
Do something like this:
var w
if (result[0]) {
w = result[0].name
} else {
//your logic to handle this scenario
}
That assumes that whatever db querying library you use will return an array, even if empty. If it returns undefined instead of an empty array, your if statement would need to look more like: if (result && result[0])