I am trying pass this object as parameter
{'0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE': '100000000000000000'}
In this function, to update mysql JSON column, but get Error:
ER_BAD_FIELD_ERROR: Unknown column '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeE
eeeeeeeEEeE' in 'field list'
HOW TO pass this Object parameter correctly?
exports.update = async (jsonObj, address) => {
console.log("jsonObj", jsonObj);
const q = "UPDATE list SET balance = ? WHERE address = ?";
try {
await query(q, [jsonObj, address]);
console.log("Updated", address);
return "Ok";
} catch (err) {
throw err;
}
};
The problem is that your SQL is wrong. You will probably want to use JSON_SET('the name of your JSON column','the key of the key/value pair you want to update','the new value you want for that key/value pair).
Related
I managed to display data from database next I try to add data to my database here is my code snippet >>>
exports.tambahData = (req, res) => {
var keyy = req.body.keyy;
var valuee = req.body.valuee;
var brand = req.body.brand;
var productName = req.body.productName;
connection.query(
"INSERT INTO `keranjang` (keyy,valuee,brand,productName) VALUES(?,?,?,?,)",
[keyy, valuee, brand, productName],
(err, rows, fields) => {
if (err) {
console.log(err);
} else {
response.ok("successfully added ", res);
}
}
);
};
but i getting an error below
ERROR:er_parse_error: you have an error in your sql syntax; check the manual that corresponds to your mariadb server version for the right syntax to use near
Any Ideas on how to solve it
You have an additional comma (,) in your sql statement
INSERT INTO `keranjang` (keyy,valuee,brand,productName) VALUES(?,?,?,?,)
Try changing it to
INSERT INTO `keranjang` (keyy,valuee,brand,productName) VALUES(?,?,?,?)
Let me know if this works for you.
"INSERT INTO keranjang (keyy,valuee,brand,productName) VALUES(?,?,?,?,)",
Correct this line to
"INSERT INTO keranjang (keyy,valuee,brand,productName) VALUES(?,?,?,?)",
I am trying to write a procedure that logs that an Item was retrieved when the procedure is used. Right now, I can retrieve the items but I am just stuck on adding a single key and value to the item as I loop through the collection:
Here is my code:
function example(prefix) {
var collection = getContext().getCollection();
collection.chain().filter(function (doc) {
return doc.textStatus = "delivered";
}).map(function (doc) {
doc.note = "test";
var isAccepted = collection.replaceDocument(doc._self, doc, function (err) {
if (err) throw err;
});
if (!isAccepted) throw new Error("replaceDocument(metaItem) returned false.");
}).value();}
This is giving me this message:
Message: {"Errors":["Encountered exception while executing function. Exception = Error: {"Errors":["Requests originating from scripts cannot reference partition keys other than the one for which client request was submitted."]}
I have also tried setting the partition key of the doc (e.g. doc.partitionKey = "sid"), though I would assume it is set as the docs are being pulled from the collect.
Update
I thought that is code was sending docs to map function but when I checked again, it was not. I thought that my partition key was "/sid" or "sid" and entered those as strings for parameters of the stored procedure. This was after adding === and sid on filters. This produced no errors, but I could not log or change any docs.
Please change return doc.textStatus = "delivered"; to return doc.textStatus == "delivered" && doc.partitionKey == "sid"; to have a try. It works for me.
Update
When you want to execute your SP, you need to pass your partition key value not your partition key path. According to your screenshot, your partition key path is /sid and your partition key value is undefined.
So your SP should be like this:
function example(partition_key_value) {
var collection = getContext().getCollection();
if(!partition_key_value){
partition_key_value = undefined;
}
collection.chain().filter(function (doc) {
return doc.textStatus == "delivered" && doc.sid== partition_key_value;
}).map(function (doc) {
doc.note = "test";
var isAccepted = collection.replaceDocument(doc._self, doc,function (err) {
if (err) throw err;
});
if (!isAccepted) throw new Error("replaceDocument(metaItem) returned false.");
}).value();
}
And execute your SP like this:
I am pretty new to nodejs and am using it to construct an api with a mysql database and have run into an issue where I am unable to execute mysql queries sequentially.
The database structure is that there are three tables. Table a in a one to many relation with table b, which is in a one to many relation with table c.
I need a GET endpoint where aid is given and it returns a result with an array of items of b with the array of items of c nested inside it.
Sample Result:
{
logcode: "",
logmessage: "",
bitems: [{
bitemid: 1
citems: [{
citemid: 1
} {
citemid: 2
}]
}{
bitemid: 2
citems: [{
citemid: 3
}]
}]
}
Currently I am attempting to do this by first executing a query where I retrieve all the values of type b that correspond to the received key of entity a and then running a foreach loop over the results and extracting the bitem ids and then running another query within the foreach loop to get all items of table c with that specific foreign key.
async function (req, res) {
let functionname = 'getAllItems'
const conLocalPool = db.conLocalPool.promise();
var data = {}
const atoken = req.get('token');
var str = ``;
str = `call ${functionname}('${atoken}')`;
console.log(str);
try {
const [rows, fields] = await conLocalPool.query(str)
data = rows[0][0]
if (data.logcode === 20100) {
data.bitems = rows[1];
data.bitems.forEach(async (bitem) => {
var stmt = `Select * from \`table-c\` where bitemid=${bitem.id}`
try {
const [citemrows, citemfields] = await conLocalPool.query(stmt);
console.log(citemrows[1])
bitem.citems = citemrows[1];
return true;
}
catch (err) {
console.log(err);
return false;
}
})
}
res.status(200).send(data);
return true;
}
catch (err) {
res.status(500).send({
error: err.message
});
return false;
}
}
Using this function, I am able to get a response which contains all the bitems related to the aitemtoken but without the citems related to each individual bitem.
I would like some help on how to execute the first query and then the later queries based on the response that it retrieves.
According to your last comment, I'm sure that you can achieve it by doing JOIN. There are a few ways to do it but consider this example below:
SELECT * FROM owner o
JOIN dogs d ON o.id=d.owner_id
JOIN dog_toys t ON d.id=t.dog_id
WHERE o.id=1;
Assuming that you have 3 tables (owner, dogs & dog_toys) and each of the table have a relation of owner.id=dogs.owner_id and dogs.id=dog_toys.dog_id, you can simply JOIN all three of them in one query and modify the returned results in SELECT.
I've created a sample fiddle here : https://www.db-fiddle.com/f/ukBgL4M3NzkyTDC6nMGkJn/1
I write some code in the server-side, in node js for update MySQL database.
this is my code:
exports.addPlayerToMatch = function(uid,matchId){
return new Promise(function(resolve,reject){
dbFunctions.getPlayerUids(matchId).then(function(rows){
playerUids = JSON.parse(rows[0].uids_of_players);
playerUids.push(uid);
console.log("new player uids: " +playerUids);
numberOfPlayers = playerUids.length;
db.query('UPDATE current_matches SET number_of_players = ?,
uids_of_players = ? WHERE id = ?' ,[numberOfPlayers,playerUids,matchId],
function (err, rows) {
if (err){ console.log("ErrorForAddPlayerToMatch: "+err);}
});
resolve(numberOfPlayers);
});
});
};
and this is the error:
ErrorForAddPlayerToMatch: Error: ER_PARSE_ERROR: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''3d8b7210fc1999bf191b0e1f7d744269' WHERE id = 29' at line 1
I have no idea !!
help, please.
The Problem was that I forgot to turn an array into a JSON object again before using it in the query.
it will solve with something like this:
var playerUids = JSON.stringify(playerUids);
and then use it in the query.
I'm trying to figure out how to do dynamic queries in node.js with node-mysql. Which table and fields to insert and update is based on users' request from the data object. I thought of creating a module to store different queries like the following but no luck. It gave me this error:
TypeError: Object function (){
var likes = 'INSERT IGNORE INTO item (id,like_type) VALUES(?,?)';
return likes;
} has no method 'replace'
app.js
var queries = require('./queries');
.....
socket.on("like",function(data){
var table_file = data[0].table;
var d = data[1];
connection.query(queries[table_file]
,[d.id,d.like_type],function(err,rows,fields){
if(err){ throw err;}
console.log(rows);
});
queries.js:
module.exports = {
item_like:function(){
var likes = 'INSERT IGNORE INTO item (id,like_type) VALUES(?,?)';
return likes;
},
people:function(){
var likes = 'INSERT IGNORE INTO people (id,like_type) VALUES(?,?)';
return likes;
}
}
Here's the data object sent to socket:
data object: {table:item_like},{id:1,like_type:1};
Change your exports in queries.js to be set to the SQL strings instead of functions, since that is how you're treating them currently:
module.exports = {
item_like: 'INSERT IGNORE INTO item (id,like_type) VALUES(?,?)',
people: 'INSERT IGNORE INTO people (id,like_type) VALUES(?,?)'
}