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
Related
I am trying to send post request to update state of a record in database. I'm using pg-pool to talk to database. My code is failing in the second query where I get 'This socket has been ended by other party'. Even though I get run state update response I still get the error.
router.post('/cancel', function(reg, res, next {
db.getclient('tasksys', function(err, client, done){
if(err){
done();
return next(err);
}
var statement = "select * from runs";
let runId;
client.query (statement, function(err, result){
done () ;
if(err)
return next(err);
} else{
runId = result.rows [0][' id']
var statement= "update runs set state 'pending' where id=$1";
var args = [runId];
client.query(statement, args, function(err, result){
done()
if(err){
return next(err);
}else{
return res.send('Run state updated')
}
});
}
});
});
});
Error:This socker has been ended by other party
at Scoket.writeafterFIN [as write]
at Connection.end(...connection.js)
at Client end(...lib/client.js)
atPool.remove (...pg-pool/index.js)
at Timeout(...pg-pool/index.js)
at listenOnTimeout(<node_internal/internal/timer.js)
at processTimers(internal/timers.js){code:'EPIPE', stack:'Error:This socket has been ended by the other party'}```
I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
I've taken this apart several different ways. The find happens after the remove, and the find never finds anything. If I comment out the this.accounts.remove... the find works. If I leave the remove line in there it doesn't. My understanding of cucumberjs, mongo client and node indicates that the find should work.
I've even tried moving the remove/find sequence into its own file, and it works there. It seems to be only when I'm running it in cucumber that the sequence fails. I suspect because of the way of cucumber loads the files, but I'm not sure.
Can someone help me figure out how to get this working?
World.js:
var db = new Db('FlashCards', new Server('localhost', 27017));
db.open(function(err, opened) {
if (err) {
console.log("error opening: ", err);
done(err);
}
db = opened;
});
var {
defineSupportCode
} = require('cucumber');
function CustomWorld() {
this.db = db;
this.accounts = db.collection('accounts');
hooks.js:
Before(function(result, done) {
//comment this out, and leave a done(), it works!!!!
this.accounts.remove(function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
})
});
user_steps.js:
Then('I will be registered', function(done) {
let world = this;
this.accounts.find({
username: world.user.username
}).toArray(
function(err, accounts) {
if (err) {
console.log("Error retrieveing data: ", err);
done(err);
}
console.log("Accounts found: ", accounts);
expect(accounts).to.be.ok;
expect(accounts.length).to.be.equal(1);
done();
});
});
Inovcation:
cucumber-js --compiler es6:babel-core/register
You are missing the item to be removed in the remove method. I am assuming the item to be removed is
this.accounts.remove(function(error, result){
You are missing one parameter to remove method. The parameter is query to remove. I am assuming, the remove query is {username: world.user.username}
var qry={username: world.user.username};
Please try with the following:
Before(function(result, done) { //comment this out, and leave a done(), it works!!!!
var qry={username: world.user.username};
this.accounts.remove(qry, function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
}) });
So i am actually woking on a simple program with node.Js and i have an issue using async.waterfall :
I created a function in my user model that connect the user by accessing the database, here is the code :
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
callback(err,null);
return;
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}
Using node-inspector i figured out that the main issue(I think) is that when it enters the waterfall function it doesn't execute the callback function of findOne it literally skips this and directly jump to the getPassword function (which isn't executed too).
so if someone could help me figuring out what's the problem that would be nice since i'm on it for around two days now.
Thank you
EDIT:
After adding the different missing cases of tests(which was why the callback didn't worked) I have this connection function:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
console.log('login: ',res.login);
console.log('erreur: ',err);
if (err){
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('login received :',userReceived.login);
var Ulogin = userReceived.login;
var Upassword = userReceived.password;
// function that compare the received password with the encrypted
//one
bcrypt.compare(password, Upassword, function(err, isMatch) {
if (err) {
console.log(err);
callback(err,null);
return;
}
else if (isMatch) {
console.log('Match', isMatch);
callback(null,isMatch);
}
else {
console.log('the password dont match', isMatch);
callback('pwd error',null);
}
});
},
], function(err){
if (err) {
console.error('unexpected error while connecting', err);
return false;
}
console.log('connected successfully');
return true;
});
}
And in my main file server.js i'm doing currently doing :
var connect = users.connection(login,password);
//the goal is to use the connect variable to know if the connection
//failed or not but it's 'undefined'
if(connect){
res.send('youyou connecté');
}
else {
res.send('youyou problem');
}
this absolutely don't work so i tried to use Q library but I have an error saying
"TypeError: Cannot read property 'apply' of undefined at Promise.apply"
here is the code using Q:
app.post('/signup', function (req, res) {
var login = req.body.login;
var password = req.body.password;
Q.fcall(users.connection(login,password))
.then(function (connect) {
if(connect){
res.send('connected');
}
else {
res.send('problem');
}
})
.catch(function (error) {
throw error;
})
.done();
});
but i am a little bit astonished i thought that by using async.waterfall() i told the function to wait until it received all the callbacks return so i don't understand why the connect variable is 'undefined'?
What I don't understand is - what was the flow exactly? did 'usersModel.findOne' get called?
What I see that is missing here in the getLogin function is a callback in the case that both the 'if' statement return false. in this case you'll get stuck in the first function and you won't advance to 'getPassword' function.
If this still doesn't work, please try executing the following code and report what was printed:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
console.log('getLogin - error has occured');
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
console.log('getLogin - result seems OK');
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('getPassword');
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}
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