I have arrays stacked in 1 array and I would like to insert each array per column in MySQL.
I have reached to insert all data in arrays to 1 column, but I want to insert an array per column.
Please see the screenshot and code below.
Image of array stack
con.connect(async(err)=>{
const x = await getStock()
if(err){
console.log(err);
return err;
}else{
console.log("DB ok");
}
console.log("connected");
x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
const sql ="INSERT INTO test (testCol1) VALUES ?";
const values=[
[item]
];
con.query(sql,[values],(err,result)=>{
if(err)throw err;
console.log("this have been recorded"+result);
});
}));
});
I just found a solution for this case.
It can be a little bit confusing but it is working.
Maybe there exists way easier and understandable solution, but this is the solution I have at the moment.
In the code above I was using only 1 array iterator, which was returning me an array. I decided to iterate the returned array to get each integer and insert data into MySQL, also the (test${i+1}) sets array into necessary column.
x.filter(item=>item===undefined?false:true).forEach((item,i)=>{
item.forEach(item=>{
const sql =`INSERT INTO test (test${i+1}) VALUES ?`;
const values=[
[item]
];
con.query(sql,[values],(err,result)=>{
if(err)throw err;
console.log("this have been recorded"+result);
});
})
});
Related
Previous post I will refer to later
I am making a Discord bot which uses MySQL, but that shouldn't matter, I am trying to do a blacklist database so users in it can't use my bot
This is what I got so far:
con.query("SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')", function(error, result, field) {
if(error) throw error;
});
And this kinda works, this is my output
[ RowDataPacket {
'EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = \'227090776172134400\')': 1 } ]
And the last digit works like a boolean, 1 if the row exists, 0 if it does not
But my problem is, that I can't seem to figure out how to check if it's a zero or not because it's an object
Why can't you make the query string a variable that you can later query on. For example:
let conStr = "SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')";
con.query(conStr, function(error, result, field) {
if(error) throw error;
console.log(result[conStr]); //--> 1
});
I am using: https://github.com/mysqljs/mysql to be able to access my db through javascript.
This is my current code:
connection.query(`SELECT cash FROM users WHERE id = '${userID}';`, function (error, rows, fields) {
if (error) errorHandler(msg, error);
rows = JSON.stringify(rows);
moneyArray = [];
moneyArray = JSON.parse(rows);
console.log(`Your cash: ` + moneyArray[0].cash);
});
Since rows returns [ RowDataPacket { cash: 0 } ] I had to stringify it to be able to use it, but then I parsed it back into a normal array to actually be able to get the data from it. I was wondering if there was a more efficient way to handle the RowDataPacket data because stringifying and parsing it every time I need to pull data seems inefficient.
I'm writing an application that let's a user post content (called "moments") along with one or more tags associated with that content.
I have a 3 table data model (in MySQL) that looks like this:
Table: MOMENTS, Columns: MOMENT_ID, USER_ID, TITLE, CREATE_DATE
Table: TAGS, Columns: TAG_ID, TITLE, CREATE_DATE
Table: MOMENTS_TAGS, Columns: MOMENT_ID, TAG_ID
Auto-Increment is set for: MOMENT_ID and TAG_ID
The problem I'm trying to solve (in NodeJS) is: how do I insert a new post (in MOMENT table) and 1 or more tags (in TAGS table), get their respective ID's and do a 3rd insert into the junction table (MOMENT_TAGS)?
I've already attempted to solve this (using mysqljs) by doing 3 successive queries, first MOMENTS, then TAGS, then MOMENTS_TAGS, but it fails because although the first result1.insertId returns the correct number, the 2nd result2.insertId doesn't seem to return the correct number from the TAGS table and instead simply increments the first result1.insertId.
Here is my code so far (I'm trying to get this to work for 1 tag at first):
app.post('/api/post/complex', function(req,res) {
pool.getConnection(function(err, connection) {
var preppedQuery1 = "INSERT INTO MOMENTS (USER_ID, TITLE, CREATE_DATE) VALUES ('justatest#gmail.com','test moment title','2016-08-08')";
connection.query(preppedQuery1, function(err1, result1) {
if (err1) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery2 = "INSERT INTO TAGS (TITLE, CREATE_DATE,USER_ID) VALUES ('TEST TAG', '2016-09-08','justatest#gmail.com')";
connection.query(preppedQuery1, function(err2, result2) {
if (err2) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery3 = "INSERT INTO MOMENTS_TAGS (MOMENT_ID, TAG_ID) VALUES (" + result1.insertId + "," + result2.insertId + ")";
//At this point if result.insertId is 100, result2.insertId is always 101 instead of coming from the TAGS table
//Why isn't result2.insertId the auto-incremented number from the TAGS table insert?
connection.query(preppedQuery3, function(err3, result3) {
if (err3) {
res.send('ERROR');
connection.release();
}
else {
console.log(result3); //not really needed
res.send('OK'); //everything worked
connection.release();
}
});
}
});
}
});
});
});
It looks like you're running preppedQuery1 twice.
Typo here:
(Assuming that's not just a typo in the post and actually exists in your source...)
Resolved: typo in 2nd preppedQuery (used 1 again, instead of 2).
Tested things and correct insertId is being assigned.
Im trying to find the index of an object inside an array and return that index so that I can update my collection with the returned index. Consider this structure in mongoDb:
{
"_id" : ObjectId("571e32d44990e27409df4bb5”),
"association" : ”f",
"events" : [
{
"event" : ”eventtest”,
"students" : [
{
"session" : "beP--kELak7gcFQLN6-o_AdTkJA8eYcp",
"name" : ”Student",
"email" : ”email#example.com”,
"checkedIn" : false
},
{
"name" : "newstudent",
"email" : "newemail",
"checkedIn" : false
}
]
}
}
When I enter the students email in a form I want to set its "checkedIn" value to true. Using mongodb, express and node js this is what I've managed to do so far:
MongoClient.connect(url, function(err, db){
if (err){
console.log("Unable to connect to server");
} else {
console.log('Connected to server');
var collection = db.collection('associations');
//indexes should be set dynamically where the emails match
var eventIndex = 0;
var studentIndex = 1;
var setModifier = { $set: {} };
setModifier.$set['events.' + eventIndex + '.students.' + studentIndex + '.checkedIn'] = true;
collection.update({
association: assoc,
"events.event": event,
"events.students.email": req.body.email
}, setModifier, function(err, user){
if(err) {
console.log(err);
} else{
res.redirect("checkin");
}
db.close();
});
}
});
This works just fine, I need to query the student with, for example, the email of "newemail" and set the studentIndex to 1, and the same to return a value of 0 for the event: "eventtest".
I've found that you can use mapReduce or aggregation to find an items index in an array but I'm not sure that this would work for objects and I have no idea where to start. Someone suggested processing this on the client side as mapReduce wasn't recommended in the first place, but this seems like quite a lot of hassle.
Here are some links that might shed to some light over what I'm trying to accomplish.
Retrieve only the queried element in an object array in MongoDB collection
Retrieve index of item in array in MongoDB
Using MongoDB's positional operator $ in a deeply nested document query
function to return index of an object in a deeply nested array
EDIT:
I found this article aswell, Mongodb sort inner array
Maybe it could work if I aggregate the inner array of students and sort the student objects so that the corresponding student that matches the email is sorted at the top of the list while still keeping the rest of the structure in the whole document the same. This way the student that should be checked in always has an index of 0? Is this bad practice? It seems to me that this is a a lot of hassle for a rather simple task.
So I have set up a query builder that builds a query based on the users interaction with the data filtration area on the front end which contains a lot of radio buttons and dropdown boxes etc. Similar to what eBays data filtration function provided on their website.
My Query Builder so far:
app.post('/user/test',function(req, res) {
var query = {};
if (req.body.region){
query.region = req.body.region
console.log(query.region)
}
if(req.body.sector){
query.sector = req.body.sector
console.log(query.sector)
}
if(req.body.client){
query.client = req.body.client
console.log(query.client)
}
Project.find(query, function(err, project){
if (err){
res.send(err);
}
console.log(project);
res.json(project);
});
});
Now the above works very well. I can send filtration options in any scenario and it will bring back the required result. For example I can only send the region name and it will give me all the data that belongs to that region or I can send region name, sector name and it will further filter down the data that matches region and sector name sent and so on.
The Issue:
Now my database contains an array of data like:
words: ["book", "table", "pen"]
Each object in the database will have this array. So if there are 100 objects in the database each has one of these will have the "words" array with different or similar values.
I want to be able to send multiple options like "table" , "pen" to my database and get all the objects that contains the those two options within the data array.
To achieve that I did the following:
if (req.body.sol){
var arr = [];
arr.push(req.body.sol)
query.words = {words: {$in: arr}}
}
The above Did not work.
But if I make the following changes to this line:
From
query.words = {words: {$in: arr}}
to
query = {words: {$in: arr}}
Making the above change does work but then it does not build the remaining queries. It only builds the "$in" query.
Any idea how I can fix this?
you can simply write the query like
query.words = {$in: arr}
This way you would be able to build rest of the query.
the reason why query.words = {words: {$in: arr}} fails is that the query becomes{words:{words: {$in: arr}}}, which is not what you want, since its trying to find words inside words.
instead using query.words = {$in: arr} will make your query {words: {$in: arr}
You can use the bracket notation to add the $in operator in your query properties:
if (req.body.sol){
var arr = [],
obj = {};
arr.push(req.body.sol);
obj["$in"] = arr;
query.words = obj;
}