I am very new to express.js and programming in general. I am trying to learn how to retrieve data from database(Mongodb) and send it to html file or javascript. I managed to retrieve data and console.log it. I have this code which gets the array called 'data' from the database and console.log it. I want to pass the data which is array of locations to my html file which alert the location. I thought I can simply put the data in a javascript file as a node module and call the variable in that in the other javascript file. and now I know that if it was jade I could easily add the variable after res.render. how would it work if I am using html and am having a separate javascript file?
here is my app.js code:
var placeFinder = require ("./public/assets/js/data.js");
app.get('/test', function(req, res){
placeFinder(function(err, data){
if(err){
return res.send(500);
}
res.locals.place = data;
console.log(data);
res.render('test', {data: data});
});
});
and here is my data.js code:
var mongoose = require ('mongoose');
function getPlaces(callback){
var data = new Array();
mongoose.model('stories').find({},function(err, companies) {
if(err){
return callback(err, data);
}
for (var i = 0; i < companies.length; i++) {
data[i] = JSON.stringify(companies[i].place);
}
return callback(null, data);
});
}
module.exports = getPlaces;
and here is my html with js code:
<html>
<head>
<title>test</title>
<script>
$('button.showlocation').click( function(){
var new = {{data}};
document.write(new);
}
</script>
</head>
<body>
<button class="showlocation btn btn-info">Click Here!</button>
</body>
</html>
Thanks alot