Reputation: 525
I am prepared statements in nodejs , to insert data into database using posgresql. I can tell where I am going wrong , but each I get this error (error: syntax error at or near "$")
Please Help.
class Employees {
constructor(user) {
this.client = require("../database");
this.createTable();
// this.dropTable();
this.bcrypt = require("bcrypt");
this.user = user;
}
createTable() {
this.client.query(
"CREATE TABLE IF NOT EXISTS employees(userId SERIAL,firstName varchar(255) NOT NULL,lastName varchar(255) NOT NULL,email varchar(255) NOT NULL,password varchar(255) NOT NULL,gender varchar(255) NOT NULL,jobRole varchar(255) NOT NULL,department varchar(255) NOT NULL,address varchar(255) NOT NULL,PRIMARY KEY (userId))",
(err, res) => {
console.log("ERROR ==> " + err);
console.log("RESPONSE ==> " + res);
}
);
}
// dropTable() {
// this.client.query("DROP TABLE employees", (err, res)=>{
// console.log("ERROR ==> " + err);
// console.log("RESPONSE ==> " + res);
// })
// }
// create employees and save into the databse
async save() {
this.bcrypt.hash(this.user.password, 10).then(hash => {
// let sql = "INSERT INTO Teamwork.employees(userId,firstName,lastName,email,password,gender,jobRole,department,address) VALUES($fn, $ln, $em, $pwd, $gen, $job,$dep, $addr)";
let params = [
"",
this.user.firstName,
this.user.lastName,
this.user.email,
this.user.password,
this.user.gender,
this.user.jobRole,
this.user.department,
this.user.address
];
this.client.query(
"INSERT into employees (userId, firstName, lastName, email, password, gender, jobRole, department, address) VALUES($id, $1, $2, $3, $4, $5, $6, $7, $8) RETURNING userId",
params,
(err, res) => {
console.log("ERROR ==> " + err);
console.log("RESPONSE ==> " + res);
}
);
// .catch( (error)=>{
// console.log(error);
// })
// .finally( ()=>this.client.end())
});
}
}
module.exports = Employees;
The above is my code snippet.
Upvotes: 0
Views: 1126
Reputation: 18909
Remove the userID in the insert statement as that field is marked serial so should not be included in the statement.
Upvotes: 1