This is my code in my js file..and the outcome stores in array result and i can see that by console.log (within js file).... i want to take the result and print in my ejs file.. could you pls guide how to take this ..
my js file contains the sorting function is written as below:
function sortEvents(){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
var mysort = { entryfees: -1 };
dbo.collection("eventtrans").find().sort(mysort).toArray(function(err, result)
{
if (err) throw err;
console.log(result);
db.close();
return(result);
})
})
}
module.exports = sortEvents;
my app.js file is as below
the sortEvents is getting called and it works correctly, as i can see the console.log value in my console
sortEvents = require("./sortevent.js");
app.get("/prlist",function(req,res){
console.log("inside prlist")
var result=sortEvents();
res.render("prlist.ejs",{prlist:result});
});
my ejs prlist.ejs file is as below .. i am trying to print the result values in my ejs screen ..have included the ejs tags as well ..but it is not recognizing prlist ...
<% prlist.forEach(function(abc){ %>
<div class="col-md-4 col-sm-6">
<div >
<h6><%= abc._id %></h6>
<h6><%= abc.eventname %></h6>
<hr>
</div>
</div>
<% }); %>
when i run the app.js , the error i am getting is like below
TypeError: C:\Suren\NewProject\views\prlist.ejs:22
20|
21| <div class="row text-center" style="display:flex; flex-wrap: wrap;">
>> 22| <% prlist.forEach(function(abc){ %>
23| <div class="col-md-4 col-sm-6">
24| <div >
25| <h6><%= abc._id %></h6>
Cannot read property 'forEach' of undefined
at eval (C:\Suren\NewProject\views\prlist.ejs:11:15)
could you pls help where i am going wrong..
i have changed the code this way ..but not helping..
app.get("/prlist",function(req,res){
console.log("inside prlist")
//var result= sortEvents();
sortEvents(function(result) {
console.log(results);
// Code that depends on 'result'
res.render("prlist.ejs",{prlist:result});
});
});
and my js file looks now as
function sortEvents(result){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
var mysort = { entryfees: -1 };
dbo.collection("eventtrans").find().sort(mysort).toArray(function(err, result)
{
if (err) throw err;
console.log("inside sortevent");
console.log(result);
db.close();
return(result);
})
})
}