not equal to not working in postgresql query - node.js

if (req.body.positionDetails && req.body.positionDetails.length > 0) {
let total = req.body.positionDetails.length;
for (let i = 0; i < total; i++) {
db.query('SELECT * FROM position WHERE position <> $1',[req.body.positionDetails[i].position],function(err,p) {
console.log(p.rows)
});
}
}
It is selecting all the values from the database without checking the condition. How to solve this??
data is like
"positionDetails":[{"position":"manager"},{"position":"developer"}] and it is from postman.

Your prepared statement looks off to me. Try using ? as a placeholder for the position in your query.
db.query(
'SELECT * FROM position WHERE position <> ?', [req.body.positionDetails[i].position],
function(err, p) {
console.log(p.rows)
});
If this fixes the problem, then I suggest that you were comparing the position against the literal string $1, and every comparison failed resulting in every record appearing in the result set.

Related

How to update a table from a JSON object where the conditions are in a JSON object?

I want to update a taable from a JSON object. The WHERE clause of the update has more than one columns. I tried this :
connexion.query("update my_table set ? where ?", [{ "param_valeur": emails }, { "param_key": "paramKey", "flotte_id": 1 }], function (err, rows) {
console.log("=================== sql =", this.sql);
if (err)
throw err;
res.send("");
});
but at runtime the WHERE clause does not have the AND keyword ! So how to fix that ?
OK, you want to use dynamic data by sending a json to MySQL WHERE query, from what I found out until now this is not a trivial operation... So, my first answer is not a good solution for your requirements so I write a new and dynamic code. (a little bit more complicated than the first answer...)
Please try the solution and let my know if this is what you want.
my answer is based on https://www.npmjs.com/package/mysql#preparing-queries, you can read this docs section for better understanding of the double question marks syntax.
let paramsSETObj = { "param_valeur": emails };
let paramsWHEREObj = { "param_key": "paramKey", "flotte_id": 1 };
// separate the question marks with comma ', '
let questionMarksForSET = this.getQuestionMarksStr(Object.keys(paramsSETObj).length, ', ');
let valuesForSETArray = this.convertObjectToArray(paramsSETObj);
// separate the question marks with 'AND'
let questionMarksForWHERE = this.getQuestionMarksStr(Object.keys(paramsWHEREObj).length, ' AND ');
let valuesForWHEREArray = this.convertObjectToArray(paramsWHEREObj);
let sql = `UPDATE my_table SET ${questionMarksForSET} WHERE ${questionMarksForWHERE}`;
let inserts = [...valuesForSETArray, ...valuesForWHEREArray];
sql = mysql.format(sql, inserts);
connexion.query(sql, function (err, rows) {
if (err)
throw err;
res.send("");
});
// Convert an object to array, where each key is before the value
module.exports.convertObjectToArray = function (obj) {
let arr = [];
for (let key in obj) {
arr.push(key);
arr.push(obj[key]);
}
return arr;
}
/**
* Get a question marks string separate each pair with the equal sign '='
* the amount of the questions marks pairs is the same as the keys of the object from the request.
* The separator in this case is comma ',' or 'AND' - this is a must for your requirement in the question.
* example:
* questionMarksForSET: ?? = ? , ?? = ?
* questionMarksForWHERE: ?? = ? AND ?? = ?
*/
module.exports.getQuestionMarksStr = function (objKeysLength, separator) {
let questionsMarks = '';
for (let i = 0; i < objKeysLength; i++) {
// if the index is not in the last object key - add the separator else add empty string
let commaOrAndSeparator = (i !== objKeysLength - 1) ? separator : '';
questionsMarks += ' ?? = ? ' + commaOrAndSeparator;
}
return questionsMarks;
}
Try this:
connexion.query('UPDATE my_table SET param_valeur = ? WHERE param_key = ? AND flotte_id = ?', [emails, "paramKey", 1], function (err, rows) {
if (err)
throw err;
res.send("");
});

Mongoose ValidationError Path required that is out of subdocument array bounds

This error is super wacky. It doesn't always fail, but when it does it looks like this.
I have some code that changes the "code" (a one character string) of elements in a subdocument array. It goes through each goal, checks to see if there's a change to be applied, and if so, applies it.
for (i = 0; i < user.goals.length; i++) {
if (transformsMap[user.goals[i].code]) {
user.goals[i].code = transformsMap[user.goals[i].code]
}
}
user.goals.sort(function (a,b) {return a.code.charCodeAt(0) - b.code.charCodeAt(0))
When I save it, sometimes I get an error like this:
'goals.3.code':
{ [ValidatorError: Path `code` is required.]
...but 3 in this case, is the length of the goals array. ie there is no goals.3 subdocument. I've tried logging user.goals and user.goals.length right before validation and they both agree that there are only 3 elements in the array.
I am totally baffled.
How about adding more checks? And also setting a default value if the if clause fails?
for (i = 0; i < user.goals.length; i++) {
if (user.goals[i] && user.goals[i].code && transformsMap[user.goals[i].code]){
user.goals[i].code = transformsMap[user.goals[i].code]
} else {
user.goals[i].code = "" // Whatever this is <-- default value.
}
}
user.goals.sort(function (a,b) {return a.code.charCodeAt(0) - b.code.charCodeAt(0))

Handsontable numeric cell globalization

I'm relatively new to js and now have to implement a handsontable into our project.
This worked well so far, but I am hitting a roadblock with globalization.
Basically, we use comma as a decimal seperator, but when I try and copy something like "100,2" into a cell designated as 'numeric,' it will show as 1002.
If the same value is entered in a cell designated as 'text' and the type is changed to numeric afterwards, the value will be shown correctly.
For this I already had to add 'de' culture to the table sourcecode.(basically copying 'en' and changing the values currently relevant to me.)
numeral.language('de', {
delimiters: {
thousands: '.',
decimal: ','
},//other non-relevant stuff here
When I copy the values directly from the table and insert them to np++ they show as 100.2 etc. However, when inserting them into handsontable the arguments-array looks as follows:
[Array[1], "paste", undefined, undefined, undefined, undefined]
0: Array[4]
0: 1 //row
1: 1 //column
2: "100.2" //previous value
3: 1002 //new value
Here's what I have tried currently:
hot.addHook("beforeChange", function () {
if (arguments[1] === "paste") {
hot.updateSettings({
cells: function (row, col, prop) {
var cellProperties = {
type: 'numeric',
language: 'en'
};
return cellProperties;
}
});
//hot.updateSettings({
// cells: function (row, col, prop) {
// var cellProperties = {
// type: 'text',
// };
// return cellProperties;
// }
//});
}
}, hot);
hot.addHook("afterChange", function () {
if (arguments[1] === "paste") {
ChangeMatrixSettings(); //reset cell properties of whole table
}
}, hot);
I hope I've made my problem clear enough, not sure if I missed something.
Are there any other ways to get the correct values back into the table? Is this currently not possible?
Thanks in advance.
You asked more than one thing, but let me see if I can help you.
As explained in handsontable numeric documentation, you can define a format of the cell. If you want '100,2' to be shown you would format as follows
format: '0.,'
You can change that to what you really need, like if you are looking for money value you could do something like
format: '0,0.00 $'
The other thing you asked about is not on the latest release, but you can check it out how it would work here
I have since implemented my own validation of input, due to other requirements we have for the table mainly in regards to showing invalid input to user.
function validateInputForNumeric(parameter) {
var value = parameter[3];
var row = parameter[0];
var col = parameter[1];
if (decimalSeperator === '') {
var tmpculture = getCurrCulture();
}
if (value !== null && value !== "") {
if (!value.match('([a-zA-Z])')) {
if (value.indexOf(thousandSeperator) !== -1) {
value = removeAndReplaceLast(value, thousandSeperator, ''); //Thousandseperators will be ignored
}
if (value.indexOf('.') !== -1 && decimalSeperator !== '.') {
//Since numeric variables are handled as '12.3' this will customize the variables to fit with the current culture
value = removeAndReplaceLast(value, '.', decimalSeperator);
}
//Add decimalseperator if string does not contain one
if (numDecimalPlaces > 0 && value.indexOf(decimalSeperator) === -1) {
value += decimalSeperator;
}
var index = value.indexOf(decimalSeperator)
var zerosToAdd = numDecimalPlaces - (value.length - index - 1);
for (var j = 0; j < zerosToAdd; j++) {
//Add zeros until numberOfDecimalPlaces is matched for uniformity in display values
value += '0';
}
if (index !== -1) {
if (numDecimalPlaces === 0) {
//Remove decimalseperator when there are no decimal places
value = value.substring(0, index)
} else {
//Cut values that have to many decimalplaces
value = value.substring(0, index + 1 + numDecimalPlaces);
}
}
if (ErrorsInTable.indexOf([row, col]) !== -1) {
RemoveCellFromErrorList(row, col);
}
} else {
AddCellToErrorList(row, col);
}
}
//console.log("r:" + row + " c:" + col + " v:" + value);
return value;
}
The inputParameter is an array, due to handsontable hooks using arrays for edit-events. parameter[2] is the old value, should this be needed at any point.
This code works reasonably fast even when copying 2k records from Excel (2s-4s).
One of my main hindrances regarding execution speed was me using the handsontable .getDataAtCell and .setDataAtCell methods to check. These don't seem to handle large tables very well ( not a critique, just an observation ). This was fixed by iterating through the data via .getData method.

How i can get latest record by using FirstOrDefault() method

Suppose i have 2 records in data base
1) 2007-12-10 10:35:31.000
2) 2008-12-10 10:35:31.000
FirstOrDefault() method will give me the first record match in sequence like 2007-12-10 10:35:31.000 but i need the latest one which is 2008-12-10 10:35:31.000
if ((from value in _names where value != null select value.ExpiryDate < now).Any())
{
return _names.FirstOrDefault();
}
You can use:
return _names.LastOrDefault();
However, your if just sends another unnecessary query (and it is a wrong query too). If you don't have any record, LastOrDefault and FirstOrDefault will return null. You can use something like this to improve the code:
var name = _names.LastOrDefault();
if(name != null)
{
return name;
}
// other code here
If you really want to use FirstOrDefault, you should order descending, like:
var name = _names.Where(n => n.ExpiryDate < now).OrderByDescending(n => n.ExpiryDate).FirstOrDefault();

sorting 2d array in node js

From the following code I am getting the appropriate output, but I want the data to come in sorted form i.e the most recent data must come on top. The data must be sorted in descending order according to the difference of current date and 'win_date'.I am new to node.js..earlier in PHP I used to do this by using function array_multisort. Can someone suggest the alternative to do the same in nodejs.
var post=[];
var sql2 ="SELECT `post_id`, `user_id`, `post`, `votes_count`, `win_date` FROM `tb_winning_posts` WHERE `group_id`=?";
connection.query(sql2,[groupId],function(err, result) {
});
for(var i=0;i<result.length;i++)
{
var timeDiff = getTimeDifference(result[i].win_date); //returns diff of cur date & given date in day,hour,min
post.push({"post_id":result[i].post_id,"post":result[i].post,"votes":result[i].votes_count,"date":timeDiff});
}
console.log(post); //getting the data in order as stored in database
Based on the answer https://stackoverflow.com/a/8837511/1903116
post.sort(function(a, b){
var keyA = a.date, keyB = b.date;
if(keyA < keyB) return 1;
if(keyA > keyB) return -1;
return 0;
});
console.log (post);

Resources