Basic ExpressJS - node.js

I am a new bie of NodeJS. I am writing a simple application with a database integration.
For Rendering i used ejs template engine to render. upto now everything working fine. succeeded in few steps as follows,
DB Integration with mongoose.
Data retrieval by avoiding routes
Finally i want to display a list on users page which is coded like wise,
app.js
app.get('/users', function(req, res){
User.find({},function (err, users) {
console.log(users)
res.render('users', { title: 'Users', users : users });
});
console.log(users)
});
users.html
<ul>
<% for(var i=0; i<users.length; i++) { %>
<li><%=i%><%=JSON.stringify(users[i]) %></li>
<% } %>
</ul>
I need a an output something coded like this: but showing undefined.
<ul>
<% for(var i=0; i<users.length; i++) { %>
<li><%=i%><%=users[i].name %></li>
<% } %>
</ul>
Can anyone suggest what would be the mistake. i am unable to print the name.

Related

Display object from knex into ejs

I am trying to display a object in my ejs file but i'm not sure what i'm doing wrong, I keep getting Object, object. I can get it to display in the terminal but once I try and display it on the ejs page it no longer works.
all what i'm trying to do is count the number of rows and display that number on my ejs pages.
app.js
// render files
app.get('/', (req, res) => {
knex.where({ID: '1'})
.select()
.count()
.from("Table")
.then((results) =>{
res.render('Page', {Lcount: results});
})
});
I've tried to do is several ways on my ejs page but I can't seem to figure it out
ejs page
<%= Lcount %> //displays object, object
<%- Lcount %> //displays object, object
<% for (var i=0; i <Lcount.length; i++ ) { %>
<%- Lcount[i] %> // displays object, object
<% } %>
<% for (let i=0; i <Lcount.length; i++ ) { %>
<%= Lcount[i] %> //displays object object
<% } %>
for anyone having a similar issue I figured out what my the problem was with my code I needed to have a alias for my count so I can call it in my ejs. Since count() is one of the cases in knex when you are not returning a row of a table you are essentially making your own row based on your query.
app.get('/', (req, res) => {
knex("Table")
.where({ ID: '1' })
.count("ID" ,{as: 'count'}) //alias setup here
.first()
.then((results) => {
res.render('Page', {
title: 'Home',
Lcount: results
});
})
});
//ejs
<% = Lcount.count %>
Your knex query return an array of object:
[ { count: '11' } ]
As i understand you want to count the records by defined ID. So it would be more readable to write your query this way:
knex("Table")
.where({ ID: '1' })
.count()
.first() // Similar to select, but only retrieves & resolves with the first record from the query.
.then((results) => {
res.render('Page', { Lcount: results });
});
The result will be an object:
{ count: '2' }
Then you can if you want pass the result this way:
res.render('Page', {
Lcount: results.count
});
In your views/Page.ejs file:
<%= Lcount %>
In case you forgot to set the view engine:
app.set('view engine', 'ejs');
I don't understand how the result could be
{ ": 26 }
It seems to be malformed. To find where it goes wrong, what you can do, is to try this simple query directly from you database and paste the result:
SELECT count(ID) FROM Table WHERE ID = 1;

Show MongoDB Query Result On ejs page

I have a router which returns a specefic user's information based on the unique Object_id from MongoDB. This works fine, and I get the correct results, but they are returned on a "blank" page as a JSON object. I want to simply fetch the result and render them on my ejs page. Here are my route:
//Here are my router.js:
router.get('/user/get:id', function (req, res) {
MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
let dbo = db.db(DBName);
const query = {_id: objectId(req.params.id)}
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
res.send(resultTasks)
db.close();
});
});
});
//Here are my file.ejs:
<div class="card" v-for="post in filteredList">
<a v-bind:href="'/user/get' + post.id">{{ post.name }}</a>
</div>
Im still new so I know this is properly basic. I guess I have to change the res.send to something else, but now sure how.
You need to loop over resultTasks in your ejs template, something like:
<% resultTasks.forEach((post) => { %>
<div class="card" v-for="post in filteredList">
<a v-bind:href="/user/get/<%= post.id %>"><%= post.name %></a>
</div>
<%}); %>
Also, you probably need to change send in your endpoint with
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
db.close();
res.render('<path of your ejs file>', {
resultTasks: resultTasks, // pass data from the server to the view
});
});

Express EJS: "Value Not Defined", But It's Inside an "If"

In Node I am sending a tasks array to some routes, and not to others. Here I am sending that tasks data:
pagedata = {
title: 'Task List App',
tasks: [{name: 'a task'}] <---
}
res.render('index', pagedata);
The markup in the EJS file has an if for that task data:
<% if (tasks) { %>
...
<% } %>
That works fine. But some pages won't have tasks, so that is why I am using if. But when I don't include a task property on the pageData object like so:
pagedata = {
title: 'Task List App'
}
res.render('index', pagedata);
I get the error tasks is not defined. I thought the whole reason you would use an if is because that data may not be there. What am I missing?
All your variables are automatically passed through "locals" object by ejs, in your view simply do this :
<% if(locals.tasks) { %>
It prevent EJS to crash if some variable aren't defined.
In addition, this locals object is also present in res.locals (if you're using express) it implies that you can also define some variable/function for your view directly in middlewares :
app.use(function(req, res, next){
res.locals.formatString = function(str){
return str.toUpperCase();
};
res.locals.globalLang = "en";
return next();
});
router.get("/index", function(req, res){
res.render("index.ejs",{title: "index"});
});
// in index.ejs
<%- locals.formatString(locals.title); %>
<%- locals.globalLang; %>
....
You can ask it like this:
<% if (tasks != undefined) { %>
...
<% } %>

In the browser showing empty while fetching data from mongodb and send to my getdata.ejs file

My index.js file get method
app.get('/getdata', function(req, res){
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('satyamsoft').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
console.log(resultArray);
});
});
res.render('pages/getdata', {holedata: resultArray});
});
My getdata.ejs file
<h2> Family Details </h2>
<ul>
<% holedata.forEach(function(data) { %>
<li><%= data.name %> - <%= data.title %> - <%= data.age %></li>
<% }); %>
</ul>
After executing the get method in the console showing data which is fetch from mongodbColnose data
But in the web page showing empty enter image description here
Am i doing anything wrong. Please help me. Advance thanks.
This might help on client side in your .ejs file -
<script>
var holedata = <%- JSON.stringify(holedata) %>;
</script>

Need help using EJS

I am exploring the use of the EJS templating system and am unsure of how to use it to get SQL data to be available to be rendered in a view.
In my app.js I have something like this:
conn.query("select name,age from people", function(err, people, moreResultSets) {
for (var i=0;i<people.length;i++){
console.log(people[i].NAME, "\t\t", people[i].AGE);
}
conn.close(function(){
console.log("Connection Closed");
});
});
And I have the following code to route the proper view:
app.get('/test1', function(req, res) {
res.render('pages/test1');
})
My confusion lies in making the people data available from the query
statement to be rendered in the view. All of the examples I have seen
have the variables defined locally inside the app.get code block and I
am unclear how to jump from that to my situation.
Thank you for any assistance you can provide!
-Andy
Render after you have the data.
app.get('/test1', function (req, res) {
conn.query("select name,age from people", function (err, people, moreResultSets) {
res.render('pages/test1', {
people: people
});
conn.close(function () {
console.log('Connection Closed');
});
});
});
HTML
<% if (people) { %>
<% for (var i = 0; i < people.length; i++) { %>
<div><%= people[i].name %></div>
<% } %>
<% } else { %>
<div>No people found</div>
<% } %>

Resources