Issue with executing prepared statement in Node JS with ibm_db module - javascript

I am new to NodeJS technology, while working on nodejs project, I got below issue.
I have implemented ibm_db module (to establish DB2 connection), and using "prepared statements" to execute 'SELECT' queries. Below query is executed without errors but console.log(result) is giving result as {fetchMode : 4}, but I am expecting COLUMN_1 results here. Can someone tell me if I am missing anything here.
db.prepare('SELECT COLUMN_1 FROM TABLE_A WHERE COLUMN_2=?', function(err, stmt){
if(err){
console.log(err);
}
stmt.execute(['CA'], function(err, result){
console.log(result);
});
});

Using an extra fetch inside of execute callback makes it possible for me to see the correct and wanted result of the query statement.
Here an example:
db.prepare('SELECT COLUMN_1 FROM TABLE_A WHERE COLUMN_2=?', function(err, stmt){
if(err){
console.log(err);
}
stmt.execute(['CA'], function(err, result){
result.fetch(function (err, data) {
if (err) {
console.error(err);
}
console.log(JSON.stringify(data));
result.closeSync();
});
});
});
The following site gave me the hint: https://groups.google.com/d/msg/node-ibm_db/AhZeeN6jFTM/MrRXSIW3DQAJ

Related

Nodejs creatng connection factory

Hi I have connection with db2 following way which works fine
require("ifxnjs").open(connectionString, function(err, con){
If(err){
console.log(err);
} else {
con.query(........){
}
}
});
I am trying to create a separate connection factory that can be called in any query. The code I have is
function confactory(){
db=require("ifxnjs).open(connectionString, function(err, conn){
if(err){} else {
console.log('connected');
}
})
return db
}
module.exports=confactory();
Than I access the connection in project
var db=require('./cofactory.js');
db.query('select * from emp', function(err, result){
if(err){}
else { cons
}
})
When I run the program I get error for
TypeError Can not read property 'query' of undefined
Please let me know how I can fix this issue. Thanks

Trouble with callbacks, error catching and MongoDB

I've been working on an application which allows me to add companies to a database. Originally my code was pure spaghetti, so I wanted to modularize it properly. For this purpose, I added routes, a controller and a dao.
This is how my code looks right now
Routes
app.post('/loadcompanies', (req, res)=> {
companiesController.loadcompany(req.body, (results)=>{
console.log(results);
res.send(200, "working!");
})
})
Controller
module.exports.loadCompany = (body, callback)=>{
companiesDao.loadCompany(body, callback);
}
Dao
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) console.log(err);
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
callback({message:"Succesfully loaded company", company:result});
});
})
}
My current concern is that working with errors when modularizing like this is confusing. I tried adding a try-catch method around the db insert and throwing and error if there is one, but that doesn't seem to work. Other things I've tried is returning the error in the callback, like this:
if (err) callback (err, null);
but I end up getting a "Can't set headers after they are sent." error.
How would you handle errors in this situation? For example, in the case that someone tries to add a duplicate entry in an unique element.
You should be able to simply do the error checking inside the callback for the insert function:
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(err, null);
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
If you get an error like you say, that's probably because the database is actually returning an error. You could also make your errors more specific, like:
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) {
callback(new Error('Connection error: ' + err.Error());
return;
}
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(new Error('Insertion error: ' + err.Error());
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
})
Here is your loadCompany done in async / await format.
Notise there is no need for error checking, errors will propagate as expected up the promise chain.
Note I've also changed loadCompany to be an async function too, so to call it you can simply do var ret = await loadCompany(conpanyInfo)
module.exports.loadCompany = async (company)=>{
let db = await MongoClient.connect(conexionString);
console.log(company);
let result = await db.collection('companies').insert(company);
return {message:"Succesfully loaded company", company:result};
}

express.js - Run python script on form-submit using POST & routing

I have installed python-shell per the instructions on this site and am able to get this code to run on test.ejs on page load:
var PythonShell = require('python-shell');
var options = {
scriptPath: '/nodeGit/scripts',
};
PythonShell.run('my_script.py', options, function (err) {
if (err) throw err;
console.log('finished');
});
I get this to run on test.ejs page load by putting it in test.js.
The portion of test.js regarding my test.ejs page looks like this:
exports.test = function(req, res,callback){
PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
// The functions below were not written by me but were left in to show how functions are written(?) in hopes that it helps
async.auto({
getData: function get_data(callback){
Images.findAll({where: {uploaded: 1}})
.then(function(getData){
callback(null, getData);
})
.catch(function(err){
console.log("*******Did not return Image Info ********");
callback(err);
});
}
function done(err, results){
callback({
userList: results.getUser,
imageList : results.getData,
user: results.verifyUser,
});
});
}
Instead of running the script on page-load, I want to call it when I submit an HTML form (& pass in the form's parameters). How would I go about that?

Node.js Facebook API

I am new to Node.js and I am having difficulties. I just wanted someone to explain where I am going wrong. I am trying to get stats from my Facebook chats and I wanted to used this API call. This is the basic code I have written.
var login = require("facebook-chat-api");
login({email: "Email", password: "Password"}, function callback (err, api) {
if(err) return console.error(err);
var threadID = chatNo;
output = api.getThreadInfo(threadNo)
console.log(output)
});
When I run this on Node.js the output is "undefined", I cant tell if its because the API call didn't work, or because I am trying to output it incorrectly. Any help would be greatly appreciated.
Output of Node.js
You should be using the callback of getThreadInfo like this
login({email: "Email", password: "Password"}, function callback (err, api) {
if(err) return console.error(err);
var threadID = chatNo;
api.getThreadInfo(threadID, function (err, info) {
console.log(err, info);
});
});

Can't list documents in mongodb collection using MongoClient in node.js

I can connect to my database from node.js using the MongoClient. I amb able to write, update and remove docs from a collection. But I am not able to retrieve data from it. This is my code:
var mongoClient=require('mongodb').MongoClient;
var mongoDbObj;
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
if(err){
console.log(err);
}else{
global.db = db;
};
var col = global.db.collection('twitter_accounts_mon');
// create
var doc1 = {'hola':'sushi'};
col.insert(doc1, function(err, result) {
callback(err);
});
// update
col.update({hola:'jordi'}, {$set:{hola:'joan'}}, {w:1}, function(err, result) {});
// delete
col.remove({hola:'jordi'}, function(err, result) {
callback(err);
});
// read
col.find().toArray(function(err, docs) {
console.log(docs);
});
What I'm trying to do in the last lines of code is to get all the documents using find() but it doesn't return any results.
Through the mongo shell, using this command I get data on screen:
db.twitter_accounts_mon.find()
I don't know what I'm doing wrong. Thanks!
the nodejs callbacks must nest, ie only search the collection once the db is open
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
var col = db.collection('twitter_accounts_mon');
coll.find({}, function(err, cursor) {
cursor.toArray(function(err, data) {
// process the data array
}
}
}
According to the MongoDB documentation on the Node.js driver, the find method does not execute the actual query, it builds an instance of a cursor that you then use to retrieve data. thus, you need to handle the result of the query.
var entireCollectionArray = col.find().toArray(function(err, items) {});
entireCollectionArray.forEach(function (element) {
console.log(element);
});

Categories

Resources