Nodejs MySQL ER_PARSE_ERROR on Insert Query errorno: 1064 - javascript

app.post('', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id' + connection.threadID)
const params = req.body;
connection.query('INSERT INTO beers SET ?', [params], (err, rows) => {
connection.release()
if (!err) {
res.send('Successfully added record of name' + params.name)
} else {
console.log(err)
}
})
console.log(req.body)
})
})

I'm not sure what kind of library you're using to communicate with the DB, but I reckon, it should look more like
connection.query('INSERT INTO beers(someColumn, someOtherColumn) VALUES (?,?)', [params.valueOfSomeColumn, params.valueOfSomeOtherColumn],...blabla the rest)
Looks like you're mixing up the INSERT and UPDATE statements. INSERT doesn't use SET
Usually this sort of basic DB libs connect the ? characters with the value from an array

Related

Save an SQL object to a file using Node.js

I need to save the object rows in a file or save it to a JSON file.
app.get('/getposts', (req, res) => {
mysqlConnection.query('Select * from posts', (err, rows, fields) => {
if (!err) console.log(rows);
else
console.log(err);
res.send(rows);
fs.writeFile('filename.json', JSON.stringify(rows), err => err && console.log(err));
This will stringify rows and write it to filename.json.

RESTful API access token mechanism

I'm developing a JavaScript/MySQL RESTful API for a business manager system using Express, Body-parser and MySQL. Currently, I am working on access tokens. Before any API call, the body must include an API key that is being verified by the API. In every API call function, I first check if the access token exists and if so, the API executes MySQL commands and sends back results.
The important thing is that I want to create a function that checks whether the access token exists and returns true or false. However, I can't figure out how to return this boolean value from the conn.query() method. Any help will be very much appreciated, I am desperate.
Here is my code:
function checkApiKey(apiKey) {
let sql = "SELECT * FROM apikeys WHERE apikey = '" + apiKey + "'";
conn.query(sql, (err, results) => {
if (err) throw err;
if (results.length > 0) return true;
return false;
});
}
app.get("/api/users",(req, res) => {
if (checkApiKey(req.body.apiKey)) {
let sql = "SELECT * FROM users";
let query = conn.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
}
});
However, the checkApiKey() method returns undefined...
Your checkApiKey function returns undefined, because your logic returns true or false within sql's callback function.
I'd recommend another approach, using checkApiKey as middleware function:
const checkApiKey = (req, res, next) => {
conn.query("SELECT * FROM apikeys WHERE apikey = ?", [req.body.apiKey], (err, result) => {
if (err) throw err
if (results)
next() // continue to next router function
else
res.status(403).end('Unauthorized') // resolve with 403
})
}
app.get("/api/users",
checkApiKey, // middleware auth function
(req, res) => {
conn.query("SELECT * FROM users", (err, results) => {
if (err) throw err;
res.send(results)
})
})

Return multiple rows from database in node

I am trying to return all the details of the product and display them in table format
I have already tried this in my api
app.get('/test',(req,res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product',(err,res) =>{
console.log(err,res)
if(err){
console.log(err);
}else{
console.log(res);
}
client.end()
})})
How do i return this res in node?
You are hiding the outside res in the route handler with the inside res of the query result.
I have to make some assumptions about your query client, but if the inside res is the array of rows, simply pass it to the res.json() function (another assumption is you are using Express).
My suggestion:
app.get('/test', (req, res) => {
const client = new Client({
connectionString: connectionString
})
client.connect()
client.query('select * from product', (err, rows) => {
console.log(err, rows)
if (err) {
console.log(err);
} else {
console.log(rows);
res.json(rows);
}
client.end()
})
});

How to beautifully display the data obtained from postgres (node js) in the table?

After the request in postgres
`
router.get('/index', (req, res, next) => {
pool.connect(function (err, client, done) {
if (err) {
console.log("Can not connect to the DB" + err);
}
client.query('SELECT * FROM cdr_final WHERE info_init #> \'{"subscriber":"9999999999"}\' ORDER BY id DESC LIMIT 20', function (err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.render('index', { cdr: result });
})
})
});`
I get the data in jsonb format
{"command":"SELECT","rowCount":18,"oid":null,
"rows":[{
{"id":754210,"info_init":{"Hour":"10","Time":"10:34:27",...,"subscriber":"99999999999",},"info_final":{"Shift":115,"OutCome":0,...,},"state":1},
{"id":754210",info_init":{"Hour":"10","Time":"10:34:27", ... "subscriber":"99999999999",},"info_final":{"Shift":115,"OutCome":0, ..."WorkMode":48,},"state":1}
}]
}
, I need
put this data in a table in index.ejs. Since only not long ago began to get acquainted with
Node js how to do it yet do not represent, in advance
thank you all for your help.

nodejs mongodb not deleteing based on id

Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.
I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.
Example
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
Suggestion
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
Yes. thank you i figured where i did wrong. see below correct answer.
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.
So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.

Categories