Home > Software design >  Display object from knex into ejs
Display object from knex into ejs

Time:02-22

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

                <% } %> 

CodePudding user response:

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');

CodePudding user response:

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;

  • Related