stored procedure in node.js - javascript

im receiving an error when running this code
Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list'
the output is this
{ employee_id: '6',
employee_name: 'test',
employee_contact: 'test' }
this is my stored procedure code
CREATE DEFINER=`root`#`localhost` PROCEDURE `test3`(
in empid int(11) ,
in name1 varchar(45) ,
in contact varchar(45)
)
BEGIN
insert into test_table (employee_id , employee_name , employee_contact)
values (empid,name1,contact);
END
this is my index.js
router.post('/test', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
// let employee_id = reqObj.employee_id
// let employee_name =reqObj.name1
// let employee_contact = reqObj.contact
var insertSql6 = "CAll test3(employee_id, employee_name, employee_contact)";
var insertValues6 = {
"employee_id": reqObj.empid,
"employee_name": reqObj.name1,
"employee_contact": reqObj.contact
};
var query = conn.query(insertSql6,insertValues6, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var test_Id = result.insertId;
res.json({
"test_id": test_Id
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});

Related

How can I retrieve the Lotus Note user job title with Node.js?

I have tried to use the following code to retrieve the Lotus user detail by Node.js.
let ActiveDirectory = require('activedirectory');
let config = {
attributes:{user: ["*"]},
url: 'ldap://mylotusdominoserver',
baseDN: 'OU=myOU,O=myOrg',
}
let ad = new ActiveDirectory(config);
ad.authenticate(user, password, function (err, auth) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
let query = "&(objectClass=*)(CN=Amy*)";
ad.find(query, (err, results) => {
if ((err) || (!results)) {
console.log('ERROR1: ' + err);
return;
}
console.log(results.other[0]);
});
}
else {
console.log('Authentication failed!');
}
});
It returns:
Authenticated!
{
dn: 'CN=Amy Tomson,OU=myOU,O=myOrg',
mail: 'amyt#myOU.myOrg',
sn: 'Amy',
cn: 'Amy Tomson'
objectclass: [Array],
givenname: 'Amy',
uid: 'amyt#myOU.myOrg',
maildomain: 'myOrg'
}
However, the return attributes do not include the working title of the user,
I have added the following attributes to force the server to return all attributes of the user.
attributes:{user: ["*"]},
However, it does not work.
My Lotus Note Domino Server version is 9.0.
Is it possible to fix it?
Finally, I use ldapjs library to fix the problem.
Here is the sample code:
const ldap = require('ldapjs');
var client = ldap.createClient({
url: 'ldap://mylotusdominoserver'
});
client.bind(userName, password, function(err) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
});
let opts = {
attributes: ['givenname', 'sn', 'uid'],
filter: '&(title=Manager)(uid=*myOU.myOrg)',
scope: "sub",
}
client.search('OU=myOU,O=myOrg', opts, function(err, search) {
if (err) {
console.log('ERROR1: ' + JSON.stringify(err));
return;
}
let results = [];
search.on('searchEntry', function(entry) {
results.push(entry.object);
});
search.on('end', function(entry) {
console.log("End:" + entry.status);
console.log(results);
client.unbind(function(err) {
console.log("Unbinded.");
if (err) {
console.log('ERROR3: ' + JSON.stringify(err));
return;
}
});
});
search.on('error', error => {
if (error) {
console.log('ERROR2: ' + JSON.stringify(error));
return;
}
});
});

Where to place the Commit block of a complex NodeJS MySQL Transaction?

I have the following code in NodeJS which works well to;
Begin a MySQL transaction;
Create an audiopost;
Update an audiopost.
Check to see if tag1 exists and if not, create it and insert into a tag table. If it does exist simply insert it to the tag table.
Commit the transaction;
But now I'd like to also check for tag2 and tag3 also.
Unfortunately, I can't figure out where and how to place the commit block
in order to keep it all as a single transaction.
If I put it just before the closing of the check for "tag1" the code won't get as far as "tag2" and "tag3". But if I put it after then the closing brackets to the connection queries are in the wrong place. Here's the code;
var mysql = require("mysql");
var express = require("express");
var connection = require("../database");
var createAudiopost = function(req, res, next){
var title = req.body.title;
var userid = req.body.userid;
var opid = req.body.opid;
var tag1 = req.body.tag1;
var tag2 = req.body.tag2;
var tag3 = req.body.tag3;
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO ?? (title,userid,opid) VALUES (?, ?, ? )', ['audioposts',title,userid,opid], function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
var audioname = userid + '-' + result.insertId + '.m4a';
var newid = result.insertId;
console.log("newid: " , newid );
connection.query('UPDATE ?? SET audioname=? WHERE audioid = ?', ['audioposts',audioname,newid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
if (tag1) {
connection.query('SELECT tagid FROM tags WHERE tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
const tagid1 = result[0].tagid;
if (result < 1) {
connection.query('INSERT INTO tags SET tagname = ?', [tag1], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log("lets see this ridiculous result", result);
const tagInsertId = result.insertId;
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagInsertId, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
});
}
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
newid = result.insertId;
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid
}); //resjson success
}); //commit
}); // insert entitytags
}); // insert tags
} // if row
else {
connection.query("INSERT INTO entitytag SET audioid = ?, tagid = ?, userid = ?", [newid, tagid1, userid], function (error, result, fields) {
if (err) {
connection.rollback(function() {
throw err;
}); //err
} //err
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
res.json({
"title" : title,
"userid" : userid,
"opid" : opid,
"insertid": newid,
"tag1": tag1
}); //resjson success
}); //commit
}) // insert entitytag2
}
}); //select tagid
}//tag1
}); //update
}); //insert
}); //begin transaction
} //createaudiopost
module.exports = createAudiopost;
Any suggestions for how I can complete such a complex transaction? I basically need to repeat the entire section of if (tag1) for tag2 and tag3.

Sending data before saving Node Js

I have this function with a Post that I want to insert the data in the database (MongoDB). First of all, I want to save the data in the model "Recetas" and after in the model "Users". And finally send the response. My problem is that is not saving in the model Users and is sending the data before saving.
This is my code
addReceta = function (req, res) {
User.findById(req.params.id, function(err, user){
if (!user){
res.send(404, 'User not found');
}
else{
fs.readFile(req.files.file.path, function (err, data) {
var id = crypto.randomBytes(16).toString("hex");
var newPath = pwd + id +req.files.file.originalFilename;
fs.writeFile(newPath, data, function (err) {
var date_created = new Date();
var date = date_created.toISOString().slice(0,10);
var receta = new Receta({
Titulo: datos2.titulo,
Username: datos2.username,
Ingredientes: datos2.ingredientes,
Dificultad: datos2.dificultad,
Descripción: datos2.descripcion,
Personas: datos2.personas,
Date_Created: date_created,
Tiempo: datos2.tiempo,
user_id: req.params.id,
imageUrl: URL + id + req.files.file.originalFilename
})
receta.save(function(err) {
if(!err) {
console.log('Created in Receta');
}
else {
console.log(error);
}
});
var UserReceta = ({
_id: receta._id,
Titulo : receta.Titulo,
Username : receta.Username,
Descripción : receta.Descripción,
Ingredientes : receta.Ingredientes,
Dificultad : receta.Dificultad,
Personas : receta.Personas,
Date_Created: date_created,
Tiempo : receta.Tiempo,
user_id : receta.user_id,
imageUrl: receta.imageUrl
});
user.Recetas.push(UserReceta);
user.save(function (err){
if (!err) {
console.log('Created in User Recetas');
}
else {
res.send(500, err);
}
});
res.send(receta);
});
});
};
});
};
Put your res.send(receta); inside the callback after saving in Users, right after the console.log:
console.log('Created in User Recetas');
res.send(receta);

Error: Cannot enqueue Query after invoking quit

when running the code below im having an Error: Cannot enqueue Query after invoking quit. i need to insert some data into two table .
can you help me to correct the code im really new here in node.js thank you so much.
Create Contact Service.
router.post('/contactinformationdetails', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
var insertSql1 = "INSERT INTO contact_person SET ? ";
var insertValues1 = {
"site_name": reqObj.sitNam,
"first_name": reqObj.firName,
"last_name": reqObj.lastName,
"position": reqObj.posId,
"contact_number": reqObj.conNum,
"organization": reqObj.orga1,
"email_add": reqObj.emaAdd1,
};
var query = conn.query(insertSql1, insertValues1, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var Contact_Id = result.insertId;
res.json({
"Cont_id": Contact_Id
});
var insertSql5 = "INSERT INTO address_contactperson SET ? ";
var insertValues5 = {
"address_name": reqObj.addNam,
"address_one": reqObj.addOne,
"address_two": reqObj.addTwo,
"city": reqObj.city,
"province": reqObj.prov
};
var query1 = conn.query(insertSql5, insertValues5, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});
You must try this with mongodb(MongoDB is an open-source document database and leading NoSQL database) the most easy and efficient way.
router.all('/todo/create', function (req, res) {
var taskcreate = req.Collection;
var task = req.body.task;
var date = req.body.date;
var status1 = req.body.status1;
var userid = req.body.userid;
var users = req.Collection;
var record = new taskcreate({
task: task,
date: date,
status1: status1,
userid: userid
});
if (task.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, userid: userid, task: task, date: date, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});

Cannot read property "rid" of undefined

[TypeError: Cannot read property 'rid' of undefined]
Is the error that I get when I try to execute this controller on my post route.
I've tested it out with Postman.
I've tried to console.log(result) but I get undefined.
My query gets executed and my row is inserted into my table. I've checked it. Password is also hashed.
The problem is that I don't get any out binds that should be returned.
Problematic code (IMO) is
...
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
...
oracle-NodeDB Wrapper
var oracledb = require('oracledb');
module.exports.OBJECT = oracledb.OBJECT;
function executeSQL(config ,sql, bindParams , options) {
return new Promise(function(resolve, reject) {
oracledb.getConnection(
config,
function(err, connection) {
if (err) {
return reject(err);
}
connection.execute(
sql,
bindParams,
options,
function(err, result) {
if (err) {
doRelease(connection);
return reject(err);
}
resolve(result);
doRelease(connection);
});
});
});
}
function doRelease(connection) {
connection.release(
function(err) {
if (err) {
console.log(err.message);
}
}
);
}
module.exports.executeSQL = executeSQL;
Controller
var database = require('../database/oracledbWrapper');
var dbconfig = require('../database/dbconfig').dbconfig;
var jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
exports.createUser = function(req, res, next) {
var user = {
email: req.body.email
};
var unhashedPassword = req.body.password;
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(unhashedPassword, salt, function(err, hash) {
if (err) {
return next(err);
}
user.hashedPassword = hash;
insertUser(user, function(err, user) {
var payload;
if (err) {
return next(err);
}
payload = {
sub: user.email,
role: user.role
};
res.status(200).json({
user: user,
token: jwt.sign(payload, config.jwtSecretKey, {expiresInMinutes: 60})
});
});
});
});
}
function insertUser(user, cb) {
var bindParams = {
email: user.email.toLowerCase(),
password: user.hashedPassword,
rid: {
type: database.NUMBER,
dir: database.BIND_OUT
},
remail: {
type: database.STRING,
dir: database.BIND_OUT
},
rrole: {
type: database.STRING,
dir: database.BIND_OUT
}
};
database.executeSQL(
dbconfig,
'insert into express_users (email, password, role ) values ( :email, :password, \'BASE\' ) returning id, email, role into :rid , :remail, :rrole',
bindParams,
{}
)
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
.catch(function(err) {
console.log(err);
next(err);
});
}
Route
var RESTfulAPICon = require('../controllers/RESTfulAPI');
var indexCon = require('../controllers/index');
var views = require('express').Router();
views.route('/users').post(RESTfulAPICon.createUser);
exports.views = views;
The problem was in my wrapper , mainly here
module.exports.OBJECT = oracledb.OBJECT;
I export only the OBJECT property , but I try to access BIND_OUT properties later on. And they are non existent.
If I do the full export like this
module.exports.OBJECT = oracledb;
Then I can access BIND_OUT properties.

Categories