Storing JSON objects in the postgreSQL using parameterized query - javascript

I am having problems with saving JSON objects in the database using parameterized queries. I am using postman to send this object on red.body
enter image description here
On my server side I havet his code:
queryController.createQuery = (req, res, next) => {
const { info }= req.body;
const sqlQuery = 'INSERT INTO test (info) VALUES ($1) RETURNING *';
db.query(sqlQuery, [info])
.then(result => {
console.log(result);
if (result) res.locals.message = "Saved the query successfully";
next();
})
.catch(err => {
return next({
log: `queryController.createQuery: ERROR: ${typeof err === 'object' ? JSON.stringify(err) : err}`,
message: { err: 'Error occurred in queryController.createQuery. Check server log for more details.'},
})
})
Why is that I still get this error: enter image description here
throw new TypeError('Client was passed a null or undefined query')
^
TypeError: Client was passed a null or undefined query
Here is my table schema:
CREATE TABLE test (
id serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
How do I format $1 correctly to get it accept it as JSON file?

Query example:
EXECUTE 'INSERT INTO test (info) VALUES ($1) RETURNING *' USING '[{"size": "Small", "quantity": 1, "product_id": 1}]'::jsonb;

Related

How to retrieve data under multiple query parameters using mongodb and javascript

I am learning to use mongodb and javascript to send requests to a database. I am provided an example for a single parameter query. How could I modify this to take 4 or 5 parameters?
console.log(req.query);
const filter = req.query._id === undefined
? {}
: { _id: req.query._id };
users.findUsers(filter, '', 0)
.then(user => {
console.log(user)
res.send(user);
})
.catch(error => {
console.error(error);
res.send({ error: 'Request failed' });
});
});```

Node.js getting Uncaught error: invalid input syntax for type integer: "NaN"

I am very new to JS and I'm trying to create an API using node.js however I'm getting the error:
Uncaught error: invalid input syntax for type integer: "NaN"
The requests are fine when I do a GET and POST request but I'm having trouble with the PUT and DELETE. I get the same error with both requests. Here is my code:
const getProfiles = (request, response) => {
pool.query('SELECT * FROM profiles', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const addProfiles = (request, response) => {
const {name, bio} = request.body
pool.query(
'INSERT INTO profiles (name, bio) VALUES ($1, $2) RETURNING id',
[name, bio],
(error) => {
if (error) {
throw error
}
response.status(201).json({status: 'success', message: 'Profile added.'})
})
}
const updateProfiles = (request, response) => {
const id = parseInt(request.params.id)
const {name, bio} = request.body
pool.query(
'UPDATE profiles SET name = $1, bio = $2 WHERE id = $3 RETURNING id',
[name, bio, id],
(error) => {
if (error) {
throw error
}
response.status(202).json({status: 'success', message: 'Profile updated with ID: ${id}'})
})
}
const deleteProfiles = (request, response) => {
const id = parseInt(request.params.id)
pool.query(
'DELETE FROM profiles WHERE id = $1', [id],
(error, results) => {
if (error) {
throw error
}
response.status(203).send(`Profile deleted with ID: ${id}`)
})
}
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
// Start server
app.listen(process.env.PORT || 3002, () => {
console.log(`Server listening`)
})
I am very much new to this and if you spot where I went wrong I would very much appreciate and explanation for me to better understand it and never make this mistake again. Thank you.
As far as I can see, req.params.id is undefined, because you are not telling express that route should receive a param.
Change this:
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
To this:
app
.route('/profiles')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
app
.route('/profiles/:id') // :id means we are expecting that param
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)
And when you do the PUT or DELETE request, the endpoint should look like this: /profiles/
The error means you'r providing a "Not a Number" (NaN) where your app expects a number (integer).
It's most probably the id in the updateProfiles or deleteProfiles, because you haven't defined it your route
app
.route('/profiles/:id')
// GET endpoint
.get(getProfiles)
// POST endpoint
.post(addProfiles)
//UPDATE endpoint
.put(updateProfiles)
// DELETE endpoint
.delete(deleteProfiles)

Getting undefined variables when inserting into mariadb

I don't know what I'm doing wrong, but I get undefined variables in my query, while the variables are set. I'm trying to create a table and then put some data into it
const obj = {
time: new Date(),
taken: 0,
given: 6.4
}
const pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'P1data'
})
pool.getConnection().then(async conn => {
let createLive = `create table if not exists live(
time datetime primary key,
taken float not null,
given float not null
)`
conn.query(createLive, (err) => {
if(err) console.error(err.message)
})
const res = await conn.query(`SHOW TABLES`)
console.log(res)
conn.end(err => {
if(err) console.error(err.message)
})
}).catch(err => {
if(err) console.error(err)
})
pool.getConnection().then(conn => {
conn.query(`INSERT INTO live(time, taken, given) VALUES (${obj.time}, ${obj.taken}, ${obj.given});`)
.then(rows => {
console.log(rows);
conn.end();
})
.catch(err => {
console.error(err)
})
}).catch(err => {
if(err) console.error(err)
})
The error I get looks like this:
Error: (conn=354, no: 1054, SQLState: 42S22) Unknown column 'undefined' in 'field list' sql: INSERT INTO live(time, taken, given) VALUES (undefined, 0, undefined); - parameters:[]
INSERT INTO (...) VALUES (...) expects the string values to be enclosed in quotes. And with your current method, also the datetime column probably will be converted from a string on insert, but you don't have any quotes in your query.
Furthermore your obj.time and obj.given seem to be undefined. Thus, your string template for the query evaluates exactly to
INSERT INTO live(time, taken, given) VALUES (undefined, 0, undefined);
So, what the query processor sees in the VALUES is 2 times the identifier undefined (it must be an identifier, because it's not enclosed in quotes) and in the current situation an identifier can only be a column.
You should check your object data
You should not create your queries with string templates, because even if you had the correct quotes, your app is widely open to SQL injections. Use parameterized queries as described in the documentation. Then the mariadb library will care about all necessary quotes and escaping.
conn.query("INSERT INTO live(time, taken, given) values (?, ?, ?)", [obj.time, obj.taken, obj.given])
.then( ...)

PG-Promise Proc Erroring Out with Unknown Parameter Type

We are attempting to write a PostgreSQL Procedure to insert data into a table. We have created the procedure and ran said procedure with the variables below and it inserts just fine. However, when we try to use pg-promise with our express server, our string parameters are being read as unknown. When we iterate over the post body, we see that each parameter is reading as the type we expect to go in, and PostgreSQL is reading integer correctly, but it isn't reading string correctly. I've attempted to use the as.text function and it sends in the parameter value as "''" but that still reads as unknown. Is there something we are missing to successfully post the data?
let createInspection = async (req, res, next) => {
try {
let params = [];
for (let prop in req.body) {
console.log(typeof req.body[prop]);
params.push(req.body[prop]);
}
console.log(params)
let data = await db.proc('Inspections_Create', params);
res.status(200)
.json({
status: 'success',
data: data,
message: 'Inserted Inspection'
});
}
catch (error) {
return next(error);
}
}

Using node mssql how do I create a database?

I tried the execute method:
const sql = require('../node_modules/mssql');
var dbname = 'AddressBook';
sql.connect('mssql://sa:1234#localhost/').then(pool => {
return pool.request().input('db_name', sql.TYPES.Text, dbname).query`select db_id(#db_name) as idn`.then(result => {
if (result[0].idn === null) {
return pool.request().input('db_name', sql.TYPES.Text, dbname).execute`create database #db_name`;
}
}).catch(err => {throw(err)});
}).catch(err => console.log(err));
I get:
message: 'The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. The RPC name is invalid.',
Also tried the query method:
return pool.request().input('db_name', sql.TYPES.Text, dbname).query`create database #db_name`;
I get
message: 'Incorrect syntax near \'#db_name\'.',
Is there a different method or am I missing something?

Categories

Resources