Display a solo element from an array sent from Express to an EJS template, along with a "next" button for cycling through each item individually

In this scenario, I have set up a route to retrieve all the items stored in the question array. However, the issue at hand is that I only want to display a single item on the ejs page instead of all the items. Additionally, I would like to include a next button that will toggle to show the next single item. View a screenshot of the problem here

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    question: []
});
app.get('/game', (req, res) => {    
    if (req.isAuthenticated()) { 
        const userId = req.user; //  iD is provided by passport.js
        User.find({ _id: userId }, (err, foundUser) => {
            foundUser.forEach((user) => {

                res.render('game', { questions: user.question }); //passing questions as an array variable to the ejs template
            });

        });

    } else {
        res.render('login');
    }
});
<%-include('partials/header')%>

    <div class="jumbotron">
        <h1 class="display-4">

            <%= questions%>// Will render the single item

        </h1>

        <hr class="my-4">
        <button class="btn btn-primary btn-lg" name="btn" value="">Previous</button>
        <button class="btn btn-primary btn-lg" name="btn" value="">Next</button>

        </p>
    </div>

<%-include('partials/footer')%>

Answer №1

If you want to paginate your data with MongoDB, you can use query limits and pages like this.

You have the flexibility to set your own limit, but for pagination purposes, it's recommended to keep it at one. In simple terms, you can manage your pages and limits by including queries in your URL as shown below:

localhost:3000/posts?page=1&limit=6 
This will display six posts from the database. Here is a solution example:

app.get('/game', (req, res) => {    
const { page = 1, limit = 1} = req.query
    if (req.isAuthenticated()) { 
        const userId = req.user; // ID provided by passport.js
       const users = User.find({ _id: userId   }).limit(limit * 1).skip((page - 1) * limit )

res.render('game', { questions: users.question })
    } else {
        res.render('login');
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to remove a property from an object that is generated by mongoose?

I am looking to query the users collection without returning the password. I want to verify if it's possible to execute javascript operations on mongodb objects. Take a look at my code snippet below: router.get("/:userId", async (req, res) => { ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

The issue with Framer motion's whileInView is that it does not animate the element when it is within the viewport in Next.js

In my current Next.js 14 project with the App Router, I decided to play around with animations using Framer Motion. One specific feature I wanted to implement was animating text elements into view as they enter the viewport. The idea is for the text to gra ...

Learn the steps to automatically route a user to a website once their Stripe payment is confirmed

On my website, there is a page dedicated to explaining the pricing plans where visitors can enter their email and credit card details. If the payment is successful, they are redirected to the create account page. However, I only want users to access the /c ...

What is the optimal method (best practice!) for generating a react component following an onClick event?

I have recently started teaching myself Reactjs and have encountered a problem. I am stuck and would like to know how I can create a new <div> in the DOM when I click on a button. When using pure JS, I used an addEventListener on a button to add / r ...

After activating the rewrite feature on Tomcat valve, JavaScript is loading twice

I've implemented the Tomcat rewrite valve in my single-page application to direct all requests, except for static resources, to my index.html file. Here is what my rewrite.config looks like: RewriteCond %{REQUEST_URI} (?!.*\.(?:jpg|png|css|js|js ...

I have successfully implemented a click effect on one image and now I wish to apply the same effect to the remaining images

I've exhausted all my options and still can't crack this puzzle. Let me break it down for you: Upon entering the page, users are greeted with a collection of images each tagged with classes (for example, img01 and img02). When an image is clicke ...

I encountered an issue where the data I passed to a component ended up being undefined

So here's the scenario: I'm working on a Next.js project where I have a context for modals. In this context, I store modal details in an array called modalBase. Additionally, I fetch data from another context (toolsContext) to pass it to componen ...

Avoid using stormpath during development stages

I've been experimenting with Stormpath using express-stormpath. Due to my poor network connection, every time the node app restarts, the page takes a long time to respond. It appears that express-stormpath is running background processes. This delay o ...

Nodejs: Dealing with Undefined JSON Objects

I'm encountering issues while trying to access a JSON object. Can you review the code and point out any mistakes I may be making? To provide clarity, I have outlined two cases that illustrate my problem: Below is the JSON data: Case 1: When attemp ...

What is the reason behind the "import statement error" that occurs during yup validation?

When running our code, we are encountering the following error: "Module not found: Can't resolve '@hookform/resolvers/yup'" ...

JSZip on Repeat: Exploring the Possibilities!

Can JSZip be used to generate multiple zip folders and files in a loop? If so, how can this be accomplished? For example: const JSZip = require("jszip"); const saveAs = require('file-saver'); const fs = require("fs"); for(let i = 0; i < 5; ...

Begin counting starting from 1 all the way up to 24, then feel free

I've developed a counter that increments from 0 to 24, and once it reaches 24: setInterval(function(){DayAndNight()}, 1000); var iState = 12; function DayAndNight() { //console.log('test'); switch(iState) ...

What could be the reason for Express not setting the JSON content type?

I have utilized Express on numerous occasions in the past, and I do not recall encountering this particular issue before. It seems like there might be a mistake on my end, but I am struggling to identify what exactly that could be. My objective is quite s ...

Issue when attempting to update the state using the spread operator

I'm currently developing a react application and I've encountered an issue. My goal is to update the state object within my reducer using parameters supplied by the action creator. To simplify, I've created an example in pure JS Here is how ...

What could be the reason for express.static failing to serve my public directory?

My dilemma lies in attempting to serve my public folder. However, I am unsure as to why my express.static line is not functioning properly. Here is the structure of my public folder: public -images ---img1.png ---blah.png -js ---app.js -pages ---index. ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

I am having trouble with Fullcalendar not loading my JSON data to display events

I've been experimenting with the fullcalendar JavaScript library, but I'm struggling to load data from my MySQL database onto the calendar. When I test my db-connect.php file, it does return the first entry in the table, yet the calendar remains ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...