I have data in my database (MongoDB) and I am finding data from DB and saving it to array. And when button is clicked on page I want to send that data to my JavaScript file and using DOM show it on page.
I am finding data form DB when page loads:
app.get('/', function(req, res) {
var ipsumTextArray = [];
Ipsum.find({}, function(err, allIpsumTexts) {
if (err) {
console.log(err);
} else {
allIpsumTexts.forEach(function(ipsum) {
ipsumTextArray.push(ipsum.text);
});
}
res.render('home');
});
});
And in my other JavaScript file I want this function to get data from DB and do whatever I want.
function randomIpsum(text) {
text.value = 'text from database'; // text is textarea where I want to show text
}
You need to render with a parameter.
app.get('/', function(req, res) {
var ipsumTextArray = [];
Ipsum.find({}, function(err, allIpsumTexts) {
if (err) {
console.log(err);
} else {
allIpsumTexts.forEach(function(ipsum) {
ipsumTextArray.push(ipsum.text);
});
}
res.render('home', { arr: ipsumTextArray });
});
});
In the front-end (view):
var arr= {{ arr }}
function randomIpsum(text) {
//text.value = 'text from database'; // text is textarea where I want to show text
text.value = arr[0]
}
OR
You can send a plain text from your nodejs.
app.get('/', function(req, res) {
var ipsumTextArray = [];
Ipsum.find({}, function(err, allIpsumTexts) {
if (err) {
console.log(err);
} else {
allIpsumTexts.forEach(function(ipsum) {
ipsumTextArray.push(ipsum.text);
});
}
res.send(ipsumTextArray);
});
});
You can get the data using jQuery in the front-end.
<button id="btn">Get Data</button>
$("#btn").on("click", function(){
$.get("/", function(data){
randomIpsum(text, data)
})
})
function randomIpsum(text, data) {
//text.value = 'text from database'; // text is textarea where I want to show text
text.value = data
}
Related
I'm trying to get 2 sets of data from my database using simple mongo db queries. since im using 2 queries, how do I then pass both results to the view? I'm getting an internal server error currently. I want to be able to show the entire list of guardians and then show how many they are in a span.
Thank you very much
here is my code:
//show guardians
router.get('/guardians', middleware.isAdmin, function (req, res) {
//ShOW ADMIN ALL guardians
User.find({ isAdmin: false }, function (err, guardian) {
if (err) {
console.log(err);
} else {
res.render('guardians', { guardian: guardian, currentUser: req.user });
}
});
//Count all guardians
User.countDocuments({isAdmin: false}, function (err, result) {
if (err) {
res.send(err);
} else {
var allGuardians = result;
res.render('guardians', { allGuardians: allGuardians });
}
});
});
You can do this:
router.get('/guardians', middleware.isAdmin, function (req, res) {
//ShOW ADMIN ALL guardians
let prom1 = User.find({ isAdmin: false })
//Count all guardians
let prom2 = User.countDocuments({isAdmin: false});
Promise.all([prom1, prom2]).then(result => {
// do your things
//results will be array and you can get
//response of prom1 in result[0]
//response of prom1 in result[1]
//pass the data to view
}).catch(err => {
//handle your error here
console.log(`Error : ${err}`);
})
});
I need to make two query's from different tables, how should i do it, to output data in new page. Now it is working with one query.
exports.getAllImages = function () {
return new Promise((resolve, reject) => {
con.query("SELECT * FROM products WHERE product_group='TRENCH
CONVECTORS'", function (err, result, fields) {
if (err) reject(err);
resolve(result);
});
});
}
//This is what i tried, but it does not work
router.get('/product/:id', async function(req, res, next) {
let filesFromFolder;
let allimages
database.retreaveImage(req.params.id).then(function(value) {
filesFromFolder = value;
});
database.getAllImages().then(function(value){
allimages = value;
})
res.render('product.ejs', {
productName: req.params.id,
data: filesFromFolder,
allimages: allimages
});
});
//This code works, and i am using it now
router.get('/product/:id', async function(req, res, next) {
let filesFromFolder;
database.retreaveImage(req.params.id).then(function(value) {
filesFromFolder = value;
res.render('product.ejs', {
productName: req.params.id,
data: filesFromFolder
});
});
});
How should i edit the code to execute two query's?
You need to render your page when you received response from both queries.
You can use Promise.all() method for this.
Promise.all([
database.retreaveImage(req.params.id),
database.getAllImages()
]).then(resultArr => {
filesFromFolder = resultArr[0];
allimages = resultArr[1];
res.render("product.ejs", {
productName: req.params.id,
data: filesFromFolder,
allimages: allimages
});
});
I'm not sure if you want a single query who retrieve data from two tables or if you want 2 different queries from 2 table...if the second, you can concatenate functions to have a linear flow of data
//This code works, and i am using it now
router.get('/product/:id/:temp', async function(req, res, next) {
let filesFromFolder;
database.retreaveImage(req.params.id).then(function(value) {
var filesFromFolder = value;
//Using a temp function
database.retreaveTemp(req.params.temp).then(function(value_temp) {
var filesFromTemp = value_temp;
res.render('product.ejs', {
productName: req.params.id,
data: filesFromFolder,
dataTemp: filesFromTemp
});
});
});
});
I am trying to build node.js + express application which consumes the data from SQL server database. But I have a problem in getting the response for my executeStatement() which is within app.get() router function. I expect my code to render an array object which I could simply use in my ejs template or view. As shown in the code below column.value is the main array of object that I want to use on the frontend.
PS: I am fairly new to the world of programming.Thank you for your help!
var express = require('express');
var tediousExpress = require('express4-tedious');
var app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
app.set('view engine', 'ejs')
app.set('views', './views')
var config = { 'contains my credentials' }
var connection = new Connection(config);
app.use(function (req, res, next) {
req.sql = tediousExpress(connection);
next();
});
app.get('/products', function (req, res ) {
/* I want to get column.value object to be rendered to my frontend
I already used res.json() here but it returns nothing*/
function executeStatement() {
request = new Request("select count * from table where ArticleId=
24588 for json path", function(err, data) {
if (err) {
console.log(err);
} else {
console.log('total rows fetched ') ;
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
column.value ;
}
});
});
connection.execSql(request) ;
}
});
You need to render within your callback to row event:
app.get('/products', function (req, res ) {
// assuming you get the datas in column.value
request = new Request("select count * from table where ArticleId=24588 for json path", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log('total rows fetched ') ;
}
connection.close();
}
request.on('row', function(columns) {
const datas = []; // <-- array to hold values
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
datas.push(column.value);
}
});
res.render('myView', { datas })
});
connection.execSql(request);
}
In your view, you can access the datas like:
<% datas.forEach(value => { %>
// do something like
// <p><%= value %></p>
<% }) %>
You are not rendering any data to be passed to the front-end, also you aren't returning the array from the function.
To neaten up your logic, you should have something like this:
app.get('/products', function(err, data) {
res.render('products', { arrData: executeStatement() }, function(err, data) {
// ...
})
})
executeStatement() { // ... }
Then in executeStatement() change column.value to return column.value
In your front-end template you can then iterate the data and output it as you wish:
<% arrData.forEach(value => { %>
// do something with each value
<% }) %>
My User model has a field of type Array with values like this
"courseId" : [
"5ac1fe64cfdda22c9c27f264",
"5ac207d5794f2910a04cc9fa",
"5ac207d5794f2910a04cc9fa"
]
My routes are configured in this way:
router.get('/:userid/vendor-dashboard', function (req, res) {
var courseID = [];
User.findById(req.params.userid, function (err, doc) {
if (err) {
res.send(err);
} else {
for (var i = 0; i < doc.courseId.length; i++) {
Course.findById(doc.courseId[i], function (err, course) {
if (err) {
console.log(err);
} else {
console.log(course.title);
courseID.push(course.title);
}
})
}
res.send(JSON.stringify(courseID));
}
})
})
First I'm finding a user and when user is found, He should find all the courses in the array and display their title.
Now, I'm able to get the title in console, but when I try to send it through res.send, it shows an empty array.
What am I doing wrong?
The main problem is that you are sending the response before getting the response from Course model.
The correct way using callback will be:
router.get('/:userid/vendor-dashboard', function(req, res) {
var courseID = [];
User.findById(req.params.userid, function(err, doc) {
if (err) {
return res.send(err);
}
var resolved = 0;
for (var i = 0; i < doc.courseId.length; i++) {
Course.findById(doc.courseId[i], function(err, course) {
if (err) {
return console.log(err);
}
courseID.push(course.title);
if (++resolved === doc.courseId.length) {
res.send(JSON.stringify(courseID));
}
})
}
})
})
I have a function that downloads the user input(currently named app.json) from browser(client) to the server
function downloadUpdate(callback) {
//Using formidable node package for downloading user input to server
var form = new formidable.IncomingForm();
form.on('fileBegin', function(name, file) {
file.path = "app.json";
});
form.parse(req, function(err, fields, files) {
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('received upload:\n\n');
res.end(util.inspect({
fields: fields,
files: files
}));
});
form.on('end', function() {
callback(null);
});
}
I have another function that takes the file downloaded above and converts it into required format(final.json) something like this.
function UpdateCode(callback) {
var obj = fs.readFileSync('app.json', 'utf8');
console.log(abc); //Im getting undefined here
var object = JSON.parse(obj);
var data2 = [];
for (var j = 0; j < object.length; j++) {
if (object[j].value == `${abc}`) {
data2.push(object[j]);
}
}
console.log(data2);
fs.appendFile('final.json', JSON.stringify(data2), function(err) {
if (err) throw err;
console.log('Saved!');
callback(null);
});
}
I used async series function to make them run in an order like this
async.series([
downloadUpload,
UpdateCode
], function(err, result) {
if (err) throw err;
else {
console.log(result);
}
});
All of this code is inside a post request. I'm getting abc from the server
app.post('/', function(req,res){
var abc = req.body.abc;
console.log(abc); //I'm getting abc here
function downloadfile(callback){
//here goes the downloadfile definition
}
function UpdateCode(){
//upload code function
}
//now i call async.series method
async.series([
downloadUpload,
UpdateCode
], function(err, result) {
if (err) throw err;
else {
console.log(result);
}
});
});
the thing is the value of abc is not going to function UploadCode and when I console log abc, I get undefined. Where am I going wrong?