How To Display MongoDB Data In Reverse In EJS

How To Display MongoDB Data In Reverse In EJS

How To Display MongoDB Data In Reverse In EJS

Hopefully, you tried everything to fetch MongoDB data and display it in reverse order in EJS (Embedded JavaScript). The problem you are facing is when you create new data and try to fetch it in your EJS file, the new one showing down below the old data, Am I right? If that is the problem you are at the right place. In this Web Development tutorial, I will help you overcome this issue.So not wasting Much time lets get started.

Recently I was working on a MEAN Stack project creating a Social Media to collaborate students and teachers in college or school. Where Student can post a new question like status we do a status update on facebook where the new update is shown on top of the old one when we refresh the page. I wanted to achieve that functionality in my Web App. I struggled a lot solving that issue. But it is not a big problem all you have to do is to use one javaScript function. As simple as that.

 Below is the Snapshot of the Problem I was facing.

Writing the New Post.

new post crankyview

New post display at the bottom of old posts after the update.

mondodb error

And a screenshot of the desired result wants I wanted.

mongodb error fixed

And this is how I achieved it.

reverse function javascript

Just use JavaScript reverse( ) function with a forEach loop to reverse the order.

Let me explain you.
ForEach loop in JacaScript is actually an updated version of basic for loop where you don't control the way of iteration with our custom iteration algorithm like we use to do with for loop

for(var i=0;i <=n; i++)
 //your content here...

As we don't have the ability to alter the predefined forEach loop algorithm. What we can do is using other javaScript functions with the loop. and thankfully we have one to reverse the order that is reverse() function.
I am fetching the post from Post schema from my models' directory and iterating over the data with a forEach loop in a reverse order with reverse() function.

That`s it. Hope this helps. If you have any problem give me a chance to help you. Thanks for reading.


Post a Comment