Save an SQL object to a file using Node.js - javascript

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.

Related

Nodejs MySQL ER_PARSE_ERROR on Insert Query errorno: 1064

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

nested mysql query get skipped in nodejs

I'm' trying to create a 'groupe' and then insert its creator as administrator in 'groupemembers' table, however the second query gets skipped
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
})
res.send(result.insertId.toString())
})
})
you need to learn callback style or even better async/await style. much more easier to code.
but for your specific concern, i think you wanted to put the res.send one line up
because that way you will call res.send AFTER the second query has executed.
router.post('/createGroupe/:userId', upload.single('file'), (req, res) => {
let groupe = req.body
// req.body containing the groupe title, description
let userId = req.params.userId
let groupeId
groupe['image'] = req.file
db.query('insert into groupes set ?', groupe, function(err, result){
if (err) throw err;
groupeId = result.insertId.toString()
db.query("insert into groupemembers set ?", [groupeId, userId, 'admin'], function (err, result){
console.log(groupeId)
if (err) return err;
res.send(result.insertId.toString())
})
})
})

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.

Node.js send JSON to client

I am new to Node.js and javascript. I have a problem which I can't solve. I have a Node application, also I am using Express.
My problem: I have a script that sends a JSON to my server. This data is then stored in my MongoDB. What i want to do now is display that data on another page. This is what i have:
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
console.log('success');
res.render('result');
});
});
});
What would be the best way to display the data stored in req.body? And could I send it to 'result'? Or should I display the data within the InsertOne-Function?
Please read the express documentation for all the details.
The JSON response can be sent using res.json() method.
Your code will look like this -
router.post('/', function(req, res, next) {
MongoClient.connect(url, function(err, db) {
var dbase = db.db("db");
dbase.collection('db').insertOne(req.body, function (err, result) {
if (err)
console.log('error');
else
res.json(result);
});
});
});

Categories