简体   繁体   English

显示从 express 传递到 ejs 模板的数组的单个项目,并使用下一个按钮切换单个项目

[英]show a single item of an array that is passed from express to ejs template with next button to toggle single item

Here I have defined a route that finds all the items inside the question array, this array is then passed to the ejs template, the problem here is I want to render a single item on ejs page, not all items, with a next button, this button should toggle the next single item I have included a screenshot of the problem在这里,我定义了一个路由来查找问题数组中的所有项目,然后将该数组传递给 ejs 模板,这里的问题是我想在 ejs 页面上呈现单个项目,而不是所有项目,并带有一个下一步按钮,这个按钮应该切换下一个项目我已经包含了问题的屏幕截图

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 }); //here questions is passed as an array variable to the ejs template
            });

        });

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

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

            <%= questions%>// this will render 

        </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')%>

You have to paginate your data using MongoDB using the query limits and page like this.您必须使用 MongoDB 使用查询限制和这样的页面对数据进行分页。

You can configure your limit to any but leave it at one if you wish to paginate it.您可以将限制配置为任何一个,但如果您希望对其进行分页,则将其保留为一个。 In other words, you can control your pages and limits using queries in your URL like this .换句话说,您可以像这样使用 URL 中的查询来控制您的页面和限制。 localhost:3000/posts?page=1&limit=6 This will bring out six posts from the database . localhost:3000/posts?page=1&limit=6这将从数据库中取出 6 个帖子。 Here's your solution这是您的解决方案

app.get('/game', (req, res) => {    
const { page = 1, limit = 1} = req.query
    if (req.isAuthenticated()) { 
        const userId = req.user; //  iD is 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');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM