I have this problem, although I managed the value of "result", the conditional expression "if" evaluates "result" always as "! == undefined" I also tried to manage with "result! == ''" but not handles it correctly. In this case I have no results from the sql query because "ricovero.cps" is not in the database and so I wrote some code to handle this case. How should I behave in order for the "if" to work correctly?
function getIdCPS(ricovero){
console.log("getIdCPS()");
querySQL = "SELECT id FROM codici_pronto_soccorso WHERE codice ='"+ricovero.cps+"'";
console.log("querySQL="+querySQL);
try{
connection.query(querySQL, function(err, result) {
if(err)
console.log(err);
if( result === undefined){
return "";
}else{
console.log("result is defined");
console.log("result=("+result+")");
return result[0].id;
}
});
}catch(e){
console.log("try/catch error:" + e);
}
}
Just put this code and monitor on console
const getIdCPS = (ricovero) => {
try {
const errorObj = { code: 400, error: 'Wrong Input' }
if (!ricovero || !ricovero.cps) {
throw errorObj;
}
const querySQL = "SELECT id FROM codici_pronto_soccorso WHERE codice ='" + ricovero.cps + "'";
connection.query(querySQL, (err, result) => {
if (err) {
throw err;
} else if (result) {
console.log(result);
return result;
} else {
throw err;
}
});
} catch (err) {
console.error(err);
throw err;
}
};
Related
I have a variable deleteFlag which is inaccessible inside a function even though the variable's scope is global.
Explanation (Pls refer my code simultaneously):
Here, I am trying to get a MongoDB collection details, the collection store a date document (result[i].date). The variable difResult stores the difference between the current date and the date fetched from MongoDB. And let's say if the value of difResult is more than a specific threshold then handle respective if-else conditions.
My if block i.e. if(difResult>20000) has a child-process, exec function and a callback function to delete MongoDB collection, now in this function I am trying to access var deleteFlag which is sort inaccessible.
Why? And how can I make is accessible inside my function?
app.js
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
console.log("Delete Flag From Collection ", +deleteFlag.toISOString());
//The above console log gives NaN or null value
//Suggest that var deleteFlag is not accessible inside this callback function
if (err) throw err;
var dbo = db.db("dbName");
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
You don't have to call the database twice you can optimize your code and use it like this
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
However if for whatever reason you need to call the database twice then store deleteFlag values in an array and then access the array wherever you like
In below function Catch is not working. unable to get the error message.
function reverseString(s) {
var ary = s.split("");
ary.reverse();
try {
console.log(ary.join(""));
} catch (err) {
console.log(err);
}
}
reverseString(1234);
Make sure that s is a string before you start doing your calculations.
Either convert s to a string:
function reverseString(s) {
var ary = String(s).split("");
ary.reverse();
try {
console.log(ary.join(""));
} catch (err) {
console.log(err);
}
}
reverseString(1234);
Or throw a custom error if s is not a string:
function reverseString(s) {
if (typeof s !== "string") throw Error("s is not a string");
// or
// if (typeof s.split !== "function") throw Error("split is not supported");
var ary = s.split("");
ary.reverse();
try {
console.log(ary.join(""));
} catch (err) {
console.log(err);
}
}
try {
reverseString(1234);
} catch (err) {
console.log("Error: " + (err && err.message));
}
try {
reverseString("1234");
} catch (err) {
console.log("Error: " + (err && err.message));
}
Just bring var ary = s.split(""); as part of the try statement and use console.error in your catch.
function reverseString(s) {
try {
var ary = s.split("");
ary.reverse();
console.log(ary.join(""));
} catch (err) {
console.error(err);
}
}
reverseString(1234);
Here is a snippet of transaction with node-mysql from the official github repo:
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO posts SET title=?', title, function (error, results, fields) {
if (error) {
return connection.rollback(function() {
throw error;
});
}
var log = 'Post ' + results.insertId + ' added';
connection.query('INSERT INTO log SET data=?', log, function (error, results, fields) {
if (error) {
return connection.rollback(function() {
throw error;
});
}
connection.commit(function(err) {
if (err) {
return connection.rollback(function() {
throw err;
});
}
console.log('success!');
});
});
});
});
I feel there are too much boilerplates over here. Isn't there a more succinct way of making a transaction, like this?:
/* invalid code */
connection.beginTransaction();
const q1 = connection.query("SELECT 1;");
const q2 = connection.query("SELECT 2;");
const q3 = connection.query("SELECT 3;");
if (q1 && q2 && q3) {
connection.commit();
else {
connection.rollback();
}
It would be synchronous in this case though.
I want to update a property in whole database.
Example I want to update property name if name=='Gaurav' then I want to replace this as name='gsb' in all documents in all collections, whether it is nested objects property. Is there any way to do this without knowing the structure of document, cause in each collection documents are of different structure. I want this query for Node JS.
What I tried is as follows. I am stuck in between.
var MongoClient = require('mongodb').MongoClient;
var config = require('../config.js');
var async = require('async');
_ = require ('lodash');
MongoClient.connect('mongodb://' + config.db_url + '/' + config.db_name, function(err, db) {
if(err) throw err;
db.listCollections().toArray(function(err, collInfos) {
async.each(collInfos,function(collectionDetails,cb){
db.collection(collectionDetails.name,function(err, collection){
if(err){
console.log(err)
}
else
{
collection.find().toArray(function(error, result) {
if(error) {
console.log(error);
}
else {
_depthFirstSearch = (collection, input) => {
let type = typeof collection;
if (type === 'string' || type === 'number' || type === 'boolean') {
return _.includes(collection.toString().toLowerCase(), input.toString().toLowerCase());
}
return _.some(collection, (item) => this._depthFirstSearch(item, input));
}
var data= _.filter(result, (item) => {
return _depthFirstSearch(item, "Gaurav");
});
console.log(data)
}
});
}
})
cb();
})
});
});
I found the solution after lots of brainstorm. I wrote below function to achieve this.
var replaceAllInsatnceInDB=function(db_url/*localhost:27017*/,db_name,propName,stringToSearch,stringToReplace){
MongoClient.connect('mongodb://' + db_url + '/' + db_name, function(err, db) {
if(err) throw err;
db.listCollections().toArray(function(err, collInfos) {
async.each(collInfos,function(collectionDetails,cb){
db.collection(collectionDetails.name,function(err, collection){
if(err){
console.log(err)
}
else
{
collection.find().toArray(function(error, result) {
if(error) {
console.log(error);
}
else {
result.forEach(function(document){
var op=function(record){
if(record!== null && record!==undefined ){
var props=Object.keys(record);
var forObject=function(obj){
if(Array.isArray(obj)){
var forArray=function(arr){
for(var j=0;j<arr.length;j++){
if(typeof arr[j] ==="string"){
if(arr[j]===stringToSearch && props[i]==propName){
arr[j]=stringToReplace
}
}
if(typeof arr[j] ==="object"){
forObject(arr[j]);
}
}
return(arr)
}
obj=forArray(obj)
}else{
op(obj);
}
return(obj);
}
for(var i=0;i<props.length;i++){
if(typeof record[props[i]] ==="string"){
if(record[props[i]]===stringToSearch && props[i]==propName){
record[props[i]]=stringToReplace
console.log()
}
}
if(typeof record[props[i]] ==="object"){
record[props[i]]=forObject(record[props[i]])
}
}
}
return(record);
}
document=op(document);
collection.update({_id : document._id},document,function(error,doc){
if(error){
console.log(error)
}else{
console.log("template updated");
}
})
})
}
});
}
})
cb();
})
});
});
}
I need some advice on how to re/write the db specific cascading code (callback) so that I can effectively return a value to the underlying if/else.
I am using restify and the db lib is node-mssql (tedious).
function authenticate(req, res, next) {
var auth = req.authorization;
var err;
if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
authFail(res);
err = false;
} else {
var sql = "SELECT ..."
var connection = new mssql.Connection(config.mssql, function(err) {
if (err) {console.log(err);}
var request = connection.request();
request.query(sql, function(err, recordset) {
if (err) {console.log(err);}
if (recordset.length === 0) {
authFail(res);
err = false; // <--- I need to be able to return this
} else {
authSuccess();
}
});
});
}
next(err);
}
I've reviewed the suggested duplicate, and while I think, I understand the issue, I can't work out the cleanest (lets be honest any) way to get this to work.
How about using Promises?
function authenticate(req, res, next) {
var auth = req.authorization;
if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
authFail(res);
next(false);
} else {
var sql = "SELECT ..."
var connection = new mssql.Connection(config.mssql, function(err) {
if (err) {console.log(err);}
var request = connection.request();
request.query(sql).then(function(recordset) {
if (recordset.length === 0) {
authFail(res);
return false; // <--- return this
} else {
authSuccess();
}
}).catch(function(err) {
console.log(err);
return err;
}).then(function(err) { next(err); });
});
}
}