NODE.JS, Express, mySQL2 : Issues appending an object inside of another object - javascript

I'm having an issue in trying to add the results of a query into an object. I am new to Node and Express so I apologize if I am making some stupid mistakes. I have been reading docs and watching videos pretty much non stop while I try to get this to work. Async is still wierd for my brain so I am sure I am doing things wrong, the function I placed seems wrong, I would appreciate so much any videos or articles you know of that could aid my comprehension as well haha!
Basically I have a table called stages, where the user can add or remove stages. I am pulling all the stages and then trying to add the projects that belong in those stages as an array of objects.
Ok so here is the code:
var myStages = []; //Global variable to hold stages.
//Get all the Stages
app.get('/', (req, res) => {
pool.getConnection((err, connection) => {
if(err) throw err;
console.log(`Connected as ID ${connection.threadId}`);
//Query
connection.query('SELECT * FROM solarcrm_stages', (err, rows) => {
connection.release();
if(!err) {
getProjects(rows);
} else {
console.log(err);
}
})
function getProjects(stages) {
myStages = stages;
Object.entries(myStages).forEach(entry => {
const[key] = entry;
connection.query('SELECT * FROM project WHERE iProjectStage = ?', [myStages[key]['iStageID']], (err, rows) => {
connection.release();
if(!err) {
myStages[key]['Projects'] = rows;
console.log(myStages); //Projects shows up as 'Projects: [ [TextRow] ]'
} else {
console.log(err);
}
});
});
}
})
})
The current result I get is this, Stage 1 has projects that should appear but shows [TextRow], Stage 2 should be empty as it is:
[
TextRow {
iStageID: 1,
sStageName: 'Stage1',
sStateIcon: 'null',
bActive: 1,
iOrderID: 1,
sStageDesc: null,
Projects: [ [TextRow] ]
},
TextRow {
iStageID: 2,
sStageName: 'Stage 2',
sStateIcon: 'null',
bActive: 1,
iOrderID: 2,
sStageDesc: null,
Projects: []
}
]
Thank you so much for any help or guidance you can offer.

Related

Avoid getting an array of id in results (mssql - node.js)

I recently started to work with mssql (SQLServer) instead of mySQL.
So I updated my routes to work with mssql.
However I encountered a problem :
When I use a join for example, with 2 tables that have a column 'Id', I got an array of Id instead of a single Id. (both ids are the same)
Is that possible to get only a single id, and not an array ?
Thank you in advance !
const query = 'SELECT sessions.*, chiffres.*, participants.*\
FROM dbo.sessions\
INNER JOIN dbo.participants ON participants.id = sessions.id\
INNER JOIN dbo.chiffres ON chiffres.id = participants.id'
return ps.prepare(query, err => {
if (err) {
return res.json({ errors: { sql: err } })
}
return ps.execute(optsValues, (err, results) => {
if (err) {
return res.json({ errors: { sql: err } })
}
return ps.unprepare(err => {
if (err) {
return res.json({ errors: { sql: err } })
}
return res.json({ sessions: results?.recordset })
})
})
})
results.recordset =>
[
{
"id": [2, 2, 2],
"num_session": "blabla"
...
}
]
I'm not familiar so much with javascript, but as the COLUMN is exactly the same name in each table and you have not aliased the columns then how do you expect the client to separate them out?
It is generally poor practice to use table.* in your queries since the table structure may change over time and your code would not immediately error and perhaps cause adverse impacts dopwnstream. Always be specific with the columns you want to choose.
Try something like this for the query:
const query = 'SELECT sessions.id as SessionID, sessions.num_session, chiffres.id as ChiffresID, chiffres.ca, participants.id as ParticipantID, participants.name\
FROM dbo.sessions\
INNER JOIN dbo.participants ON participants.id = sessions.id\
INNER JOIN dbo.chiffres ON chiffres.id = participants.id'

how to update quantity in Odoo-erp using odoo-xmlrpc library?

im trying to create a javascript function using nodejs which uses odoo-xmlrpc library to perform paiment in odoo online database.In order to do that i have to decrease the quantity of the product somehow or create a stock move.
i found this code but nothing works correctly:
var Odoo = require('odoo-xmlrpc');
var odoo = new Odoo({
url:'https://mydomain.odoo.com',
db:'mydb',
username: 'mydatabase',
password: 'password'});
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var params = [[{
'product_id': 2,
'product_uom_id':2,
'location_id':9,
'picking_type_id':2,
'location_dest_id': 13,
}]];
odoo.execute_kw('stock.move','create', params, function(err, value) {
if (err) { return console.log(err); }
console.log(value);});
});
maybe can someone help me :)

Node JS Multiple Select

Hi i am trying to use two selects in one JS file in node js and sql server. I am unable to figure out the syntax for this. I need a select to get all the persons from a table and another select to count the total number of persons in that table.Will it be possible to put those two selects in a single JS file. If so can someone help me with the syntax?
Here is the code i tried and i am getting the error
"cant Set headers after they are sent"
var sql = require("mssql");
var dbConfig = {
server: "XXXXX",
database: "XXXXX",
user: "XXXXX",
password: "XXXX",
port: 1433
};
exports.list = function(req, res){
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from PERSON', function (err, recordset) {
if (err)
console.log(err)
else
console.log(recordset)
res.render('personinfo_itwx', { data: recordset });
});
request.query('select count(*) from PERSON', function (err, recordset) {
if (err)
console.log(err)
else
console.log(recordset1)
res.render('personinfo_itwx', { data: recordset1 });
});
});
};
#Aditya I'm not sure it's the best way to do so, although I would simply make two different requests, in order to achieve what you need. As I mentioned my in my comment, easiest way, would be to use (for instance) async library. And here's example you've asked for.
WARNING: I did not look at mysql docs
const async = require('async')
// {
async.series([
function(next)
{
new sql.Request()
.query('SELECT * from PERSON', next(err, resultList))
},
function(next)
{
new sql.Request()
.query('SELECT COUNT(*) from PERSON', next(err, count))
}
], (err, result) =>
{
/*
err: String
- if any of the shown above return an error - whole chain will be canceled.
result: Array
- if both requests will be succesfull - you'll end up with an array of results
---
Now you can render both results to your template at once
*/
})
// }
Surely, if you want manipulate with errors or results once you get them - you always may push error and results to new function, play with your data, and return the callback afterwards. Like so:
function(next)
{
new sql.Request()
.query('SELECT * from PERSON', (err, resultList) =>
{
if (err)
{
return next(err, null)
}
/*
data manipulation
*/
return next(null, resultList)
})
},

Passing multiple objects to handlebars template - MongoDB, node.js, mongoskin

I have an application where I need to read from two different collections in my Mongo database and pass both the returned objects into a handlebars template.
With the code I have below I can't figure out how to get it to work, as the universityData and courseData variables aren't getting populated, not sure if this is the right way to do it anyway.
The university and course objects in the callbacks are working correctly as when I log I get the values I need.
router.get('/newcastle/G400', function(req, res) {
var db = req.db;
var universityData;
var courseData;
db.collection('universities', function(err, collection) {
collection.findOne({'code': 'N21'}, function(err, university) {
universityData = university;
console.log(university);
//res.render('course', {title: university.name, university: university, course: { "code": "G400", "name": "Computer Science", "studylength": "3 years (BSc)/4 years (MSc)", "requirements": "AAB - ABB", "satisfactionrating": "98"}});
});
});
db.collection('courses', function(err, collection) {
collection.findOne({'universitycode': 'N21', 'code': 'G400'}, function(err, course) {
courseData = course;
console.log(course);
});
});
console.log(universityData);
console.log(courseData);
res.render('course', {university: universityData, course: courseData});
});
My question is how can I get the objects from each of the queries to be passed into one template?
Any help would be appreciated as I'm fairly new to Javascript, node and Mongo.
Even though it's just "two" functions, you could use a module like async to help organize them without deeply nesting. Example:
var async = require('async');
// ...
router.get('/newcastle/G400', function(req, res) {
var db = req.db;
async.parallel([
universityData: function(callback) {
db.collection('universities', function(err, collection) {
if (err)
return callback(err);
collection.findOne({'code': 'N21'}, callback);
});
},
courseData: function(callback) {
db.collection('courses', function(err, collection) {
if (err)
return callback(err);
collection.findOne({'universitycode': 'N21', 'code': 'G400'}, callback);
});
}
], function(err, results) {
if (err)
return res.send(500);
// results === { universityData: { ... }, courseData: { ... } }
res.render('course', results);
});
});

Mongoose's model.update not working in Node.js

I have a Node.js app that is updating data in a MongoDB database using Mongoose.
I have setup the Mongoose model and I am able to successfully use the model.find, and model.remove functions, but I can't get the model.update function to work.
Can anyone help me?
/* ------------------------ Finding/Querying works ----------------------
Flot.find({ "label": "Trips Per Day"}, function (err, docs) {
res.jsonp(docs || err);
});
*/
/* ------------------------ Removing works -----------------------
Flot.remove({ "label": "Trips Per Client" }, function (err) {
if (err) return handleError(err);
res.json(err || "removed");
});
*/
var conditions = { "label": "Average Tons per Delivery" };
var update = { "label": "Average Tons per Delivery 2" };
var options = { };
var callback = function callback(err, numberAffected, rawResponse) {
if (err) return handleError(err);
console.log('Error: ', err);
console.log('NumberAffected: ', numberAffected);
console.log('RawResponse: ', rawResponse);
res.json(err || rawResponse || numberAffected );
};
Gage.update( conditions, update, options, callback );
I was able to get this working with node-mongodb-native. I'm still not sure why Mongoose wasn't working, but at least I got something to work.
var query = {"label": "Average Tons per Delivery"};
var update = {"type": "vertical"};
var options = {};
MongoClient.connect('mongodb://localhost/db', function(err, db) {
if(err) throw err;
db.collection('justgage').findAndModify(
query,
[['_id','asc']],
{$set: update},
options,
function(err, object) {
res.jsonp("Ok");
});
});

Categories