Get all tables data from SQLite DB using Node.js - javascript

Having a DB with multiple tables, I managed to get that for one table at a time and also to get the names of the tables.
However, it doesn't work to get the data for all the tables.
This is the code for getting the table names which works fine:
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/ocs_athletes.db');
router.get('/', function (req, res, next) {
db.serialize(function () {
db.all(
'SELECT name FROM sqlite_master WHERE type="table"',
function (err, rows) {
return res.send(rows);
}
);
});
});
module.exports = router;
it returns an array of this form:
[{"name":"Athlete"},{"name":"Game"},{"name":"AthletePhoto"},{"name":"AthleteResult"}]
I don't know how to get the data of these tables, I made a forEach through the elements and create a query for each table and save the data in result but doesn't work how it is.
router.get('/', function (req, res, next) {
db.serialize(function () {
db.all(
'SELECT name FROM sqlite_master WHERE type="table"',
function (err, rows) {
const result = [];
rows.forEach(
(table) => db.all('SELECT * FROM ' + table.name),
function (err, innerRows) {
result.push(innerRows);
}
);
return res.send(result);
}
);
});
});
module.exports = router;
The result is []. I guess it must be written in a way that it waits for the db to be read but I'm not sure.
Any suggestions?

Related

How to set up route parameters in Vue.js Express app

I am attempting to build a basic Vue.js Express profile interface that returns profile info of a specific user based on a route parameter id associated with each user. The .get() request in Vue.js is set up as the following:
created () {
let uri = `http://localhost:3000/users/${this.$route.params.id}`;
this.axios.get(uri).then((response) => {
this.profile = response.data;
});
},
The corresponding GET route in Express.js is set up as the following:
// mongodb
const mongo = require('mongodb').MongoClient;
const url = '...'; // connection url
const usersDB = 'users'; // users db name
app.get('/users/:id', function(req, res) {
let id = req.params.id;
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({}).sort( {username: 1} )
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
// assert.equal(null, err);
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
In the above Express route, I added let id = req.params.id with the intention of prompting this route to respond with specific user info based on req.params.id. I am not sure how to further configure this route to actually return such info based on id. I tried implementing the following in the route:
collection.find({_id: mongo.ObjectId(req.params.id)})
instead of using:
collection.find({}).sort( {username: 1} )
...but that did not work. Any idea how to set up this route to return data based on req.params.id? Thanks!
UPDATED EXPRESS ROUTE
// get all users
app.get('/users/:id', function(req, res) {
var o_id = new mongo.ObjectID(req.params.id))
// get all users
var users;
const findUsers = function(db, callback) {
const collection = db.collection('documents');
// no query filter
collection.find({'_id': o_id})
.toArray(function(err, docs) {
users = docs;
callback(docs);
});
}
mongo.connect(url, function(err, client) {
const db = client.db(usersDB);
findUsers(db, function() {
// send users
res.status(200).send(users);
client.close();
});
});
});
It seems the results aren't returned because of ObjectId comparision not working. Creating new ObjectID using the id from req.params and then doing collection.find should bring back the results
var o_id = new mongo.ObjectID(req.params.id);)
collection.find({'_id': o_id});

Data deletion from database dynamically using delete request in node.js

I am using normal http request for deleting value from mysql database using node.js. But right now, only values are deleted statically not dynamically. I want to delete the data dynamically by providing the id.
const server = http.createServer();
const reqUrl = url.parse(req.url, true);
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let sql = "Delete from students where id=12";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});
now, after running this code localhost:3000/delete only the id=12 is deleted all time. But I want to do this localhost:3000/delete?id=12 giving input values as id.
I tried to give sql command as "Delete from students where id=?" , but it gave errors. How can I solve this?
That should be simple.
You just need to receive the param from your request and append it to string.
Here's your updated code.
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let studid = req.query.id; //Get the student id
let sql = "Delete from students where id="+studid; //append it to query
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});

How can I keep my data and use it after with node-postgres

My problem is very simple, I need to put my data taken from the database in a variable but I don't know how to keep the variable defined. At the end of the pool the data went out and left the variable not defined.
So I have tried to make a res.send to send the data to the next :
.post('/route', data ,function(req, res){
...
});
but I think this is not a good idea.
.post('/musicbrainz/research/', function(req, result, next){
var nomArtiste = req.body.recherche;
var query = "SELECT idartiste * FROM artiste);";
db.query(query, (err, res) => {
if (err) {
return next(err);
}
rows = res.rows;
});
})
.get('/musicbrainz/results/', rows, function(req, res){
const results = rows;
...
My variable rows are undefined when it exits the db.query function.

SQL Server returning results twice on a single call?

I have connected a SQL Server database to a simple node.js server. When I run the code I get both recordsets and recordset returned to me. They both essentially contain the same data. I can work with this but it seems redundant and would be neater to just call exactly the records I need.
I was hoping to get an clear ELI5 explanation as mssql npm documentation is somewhat confusing in my opinion.
Here is the code below:
const express = require('express');
const cors = require('cors');
const sql = require('mssql');
const app = express();
const sqlServer = 'hasea\\SQLExpress'
const selectAllQuery = 'SELECT * FROM dbo.users';
const config = {
user: 'nbar',
password: 'nb',
server: sqlServer,
database: 'nirvanaBar'
}
// SQL Select function
function DBconn(query, res) {
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query(query, function (err, row) {
if (err) console.log(err)
res.json({
data: row
})
})
})
}
app.use(cors());
app.get('/', (req, res) => {
res.send("Hello from the server")
});
app.get('/users', (req, res) => {
//query?
//var andrew = "select * from dbo.users where firstName = 'Andrew';"
var matt = "select * from dbo.users where firstName = 'Matt';"
//DBconn(selectAllQuery,res);
DBconn(matt, res);
})
app.listen(4000, () => {
console.log(`Server started on port 4000`)
})
The results:
I can see this has being brought up before but I am not understanding what is going on nor does the documentation provide much information as to why this would be the case. I can use the data, I just thought it would be neater to return both recordsets and recordset.
Thanks in advance
This is the expected behaviour of mssql have a look at the documentation here. When you execute multiple statements it allows you to have multiple recordsets
You will notice that there is in fact 2 properties
recordset (singular)
and
recordsets (plural)
recordset (singular) refers to the first statement that is executed. In your case you can just use this
recordsets (plural) is an array of recordsets, in your case there will only be one in the array as you are only running one statement.

Mongodb, web got stuck after inserting some data

Every button is clickable and functional before I inserted data.
Render update page after insert:
But then whatever I click the Web got stuck:
But data has already been inserted.
The insert code is here:
var assert = require('assert');
var mongoose = require('mongoose');
var db = mongoose.connection;
// ...
router.post('/update', function (req, res, next) {
var item = {
result: req.body.books
};
db.collection('details-data').insertOne(item, function (err, result) {
db.close();
});
res.render('update');
});

Categories

Resources