How to get answers in a random order with handlebars?

60
March 05, 2021, at 01:50 AM

i created a quiz App with NodeJs, storing the questions and answers in MongoDb and using Hanbldebars but i ran into a problem. The code works fine but as you can see the correct answer to the questions appears always in the first place, making the game totally dumb. My question would be, how can i get the answers to be displayed in a random order?

MONGOOSE SCHEMA

const HquestionSchema = new mongoose.Schema({
question: {
    type: String,
    required: true
},
correctAnswer: {
    type: String,
    required: true
},
answer2: {
    type: String,
    required: true
},
answer3: {
    type: String,
    required: true
},
answer4: {
    type: String,
    required: true
},});

ROUTER

router.get('/', async (req, res) => {
const allQuestions = await Hquestion.find().lean();
const questions = [];
while (questions.length < 5) {
    let question = allQuestions[Math.floor(Math.random() * allQuestions.length)]
    if (!questions.includes(question)) {
        questions.push(question)
    }
}
res.render('history/history', { questions });});

HANDLEBARS

        <div>
            {{#each questions}}
            <div class="form-group mt-4 mb-4">
                <h4>{{question}}</h4>
                <input type="radio" name="question{{@index}}" id="correct{{@index}}"value="{{correctAnswer}}">{{correctAnswer}}
                <br>
                <input type="radio" name="question{{@index}}" value="{{answer2}}">{{answer2}}<br>
                <input type="radio" name="question{{@index}}" value="{{answer3}}">{{answer3}}<br>
                <input type="radio" name="question{{@index}}" value="{{answer4}}">{{answer4}}<br>
            </div>
            <div id="answer{{@index}}" role="alert">
            </div>
            <button type="button" class="btn btn-primary w-100" id="button{{@index}}">Check your answer</button>
            {{/each}}
        </div>
READ ALSO
JavaScript filter array of objects based on property values

JavaScript filter array of objects based on property values

I have an array of objects in javascriptThe contents look like this;

60
How to kill a query running by pd.read_sql and connected by sqlalchemy (or mysql.connector)

How to kill a query running by pd.read_sql and connected by sqlalchemy (or mysql.connector)

I have a Python API that receives a request from PHP code and executes some queries with pdread_sql() in a MariaDB 10

66
How to run a file in VS Code?

How to run a file in VS Code?

I am learning PHP and I have decided to use VS CodeIs there any way I can run the files without a compiler? I have looked in the output section but nothing is there

61