mongodb batch insert - Javascript not working - javascript

I want to insert bunch of records into a collection, but instead of document at a time I want to do it like a batch using "insertMany()". I wrote the script as follows:
var batch = [];
for (i=0; i<10; i++) {
names=["exam", "essay", "quiz"];
for (j=0;j<3;j++) {
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
if (mod i%3 == 0) {
batch = batch.slice(0, batch.lenght(-1));
db.scores.insertMany( batch )
batch=[];
}
}
}
The above code is not working. There are two issues: first, the array item have double quotes around them and second, the "slice" is not taking effect.
Need help in fixing the Javascript.

There are a couple of issues here:
the array item have double quotes around them
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
You want to create an object rather than a string. batch = { student: i, type: names[j], score: ..} will create an object for you.
the "slice" is not taking effect
batch = batch.slice(0, batch.lenght(-1));
You've misspelled length, and length is a property rather than a function. batch.slice() will copy the array (but you're resetting it so it's not actually necessary).

Related

How to get data from a especif Time period in InfluxDB Node-RED

I'm trying to read data from InfluxDB v1.x but only in a especific time period, Example:
Get the values of temper01 from 2021-11-09/14:00:00 to 2021-11-10/14:00:00.
i know its possible with this code :
"WHERE time >= '2021-11-09T14:00:00Z' AND time <= '2021-11-10T14:00:00Z'" But i wanna know if it is possible to use a variable instead of the direct timestamp.
i've tried this code :
msg.query = "SELECT time , Temper01, Temper02, Temper03 FROM "
+ global.get("ID_device1")
+ " WHERE time >= "
+ msg.payload;
+ " AND time <= '2021-11-18T00:00:00.000Z' " ;
but dosent matter the msg.payload value, it just get data from the very first data stored, and when i try to single quote msg.payload i get the invalid operation: time and *influxql.VarRef are not compatible" error message.
Assuming that msg.paylaod looks something like 2020-11-18T00:00:00.000Z then you have not quoted the time string you are inserting into the query.
It should look like this:
msg.query = "SELECT time , Temper01, Temper02, Temper03 FROM "
+ global.get("ID_device1")
+ " WHERE time >= '"
+ msg.payload;
+ "' AND time <= '2021-11-18T00:00:00.000Z' " ;
The difference is the ' at the end of the string on the 3rd line and again at the start of the string on the last line.
Directly comparing a working version with the version that didn't work would have shown this.

What am I receiving undefined when building this string? Javascript

I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));

binding variables to SQL statements using node-sqlite3

I am trying to convert this:
var query_string = 'SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_A = "' + item + '" ' +
'UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_B = "' + item + '";';
db.each(query_string, function (err, row) {
...
To this:
var query_string = "SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'" +
" UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'";
var placeholders = {
$table: organism + PIPE_output_table,
$score_type: score_type,
$score: cutoff['range'],
$protein: item
};
var stmt = db.prepare(query_string, placeholders, function(err) {
console.log(err);
stmt.each(function(err,row) {
...
})
}
but I keep getting this error:
Error: SQLITE_ERROR: near "$table": syntax error
But I am not sure what is syntactically wrong here since the format is as I have seen it in the API documentation. I have tried '?', '#', and ':' before each variables but none seem to be recognized.
What's wrong in my code?
Bind parameters only work for values in the WHERE clause. Table and column names (collectively called "identifiers") won't work.
"SELECT foo FROM bar WHERE this = $that" # OK
"SELECT foo FROM bar WHERE $this = 'that'" # Not OK
Normally you'd work around this by escaping and quoting identifiers and inserting them into the query. A good database library has a method call for this...
var this = db.quote_literal(input_column);
'SELECT foo FROM bar WHERE ' + this + ' = ?'
Unfortunately, node-sqlite3 doesn't appear to have one. :(
SQLite does provide a quoting function, the %w operator, but node-sqlite3 doesn't appear to make it available.
You'll have to write your own. Follow the instructions from this answer in Python and convert them to Javascript.
Ensure the string can be encoded as UTF-8.
Ensure the string does not include any NUL characters.
Replace all " with "".
Wrap the entire thing in double quotes.
I'm not very good with Javascript, so I'll leave you to code that.

Loop through severals objects js

I want to retrieve data from an object, and I need to make several iterations. I have another object inside the first.
Here is what I try to do
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers + '<div class="detail"></div>' + '<br>';
$('.test').append(itemList);
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$('.detail').append(itemDetail);
}
}
But when I did this code, the first element append, receive all the key/value from the others details objects. I only want to display the details object related with his site parent site object.
Here is a fiddle : http://jsfiddle.net/JeremDsgn/7EX6M/
Thanks!
That's because your selector $('.detail') selects all elements with class detail.
Try using the DOM instead of strings. I give you this as a personal advice. I used to append HTML via strings just like you're doing it now. Since I started using DOM objects as they are actually meant to be used, the javascript language became times more pleasant to work with.
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers;
var details = document.createElement('div');
details.className = 'detail';
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$(details).append(itemDetail);
}
$('.test').append(itemList).append(details);
}

Javascript variable, different values, same line

First of all, let me apologize for the title, as it isn't so explanatory, but I could not say it in another way.
The deal is: I am doing a javascript application, in which I have an object called "ocorrencia", which was defined like this:
var ocorrencia = new Object();
that object has several children, being filled by a method:
ocorrencia.idOcorrencia = ""+ year + month + day + hour + minute + second + milisec;
idOcorrencia is the one I am having problems with, because I am running a DataBase insert with this value, and I use it 2 times in the same insert, like:
var sql = 'INSERT INTO OCORRENCIAS (id, ocorrencia, data, resolucao, urgencia, foto) VALUES (' + ocorrencia.idOcorrencia + ', "' + ocorrencia.descricao + '", "' + ocorrencia.data + '", "' + ocorrencia.resolucao + '", "' + ocorrencia.grauUrg + '", "' + ocorrencia.idOcorrencia + '.jpg"' +')';
The insert runs great, an I have all the data inserted in the DB, BUT "id" and "foto" (which were supposed to get equal values) are giving me different values by 2 or 3 miliseconds.
How can this happen, as I am not changing "ocorrencia.idOcorrencia" ?
This is beeing tested in an Android device.
EDIT: Tested on Windows browser and the problem doesn't appear to happen.
Thank you
I guess you fill idOcorrencia on runtime? So the lag is producing this difference.
Try using a hash for the id or set it before running the SQL-query.

Categories

Resources