'How to display the amount of documents in a collection in ejs? With mongodb
I am trying to display the amount of available documents that are in a collection. The collection name is "merchant1".
This is the backend:
router.get('/merchanttrading', ensureAuthenticated, (req, res) => {
const user = req.user;
merchant1.find({}, function (error, data) {
res.render("merchanttrading", {data, user: req.user});
})
})
And this is what I am trying in the front end:
<% for (var i = 0; i < data.length; i++) { %>
<h2 id="test"><%= data[i].length%></h2>
<% } %>
<script>
<% for (var i = 0; i < data.length; i++) { %>
var documentamount = <%= data[i]%>
<% } %>
</script>
But this will just up ending beign blank. Rendering the entire document just works fine but what I want is to show the amount of current documents in the collection as a number and not the document itself.
Any help would be appreciated.
Solution 1:[1]
I have found a solution after more digging I came across this: https://www.mongodb.com/docs/manual/reference/method/db.collection.count/
Then I used that like this:
router.get('/merchanttrading', ensureAuthenticated, (req, res) => {
const user = req.user;
merchant1.count({}, function (error, data) {
res.render("merchanttrading", {data, user: req.user});
})
})
The solution seemed to easier then I thought and I was just over thinking it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SpringerJerry |
