Should I return an array or data one by one in Mongoose

I have this simple application that I created using IOS, this is a questionnaire application, whenever the user clicks the play button, he will call a request to node.js / express server

enter image description here

enter image description here

Technically, after the user clicks on the answer, he will move on to the next question

enter image description here

I am confused to use this method to get questions / question

  • retrieves all the data in one go and presents it to the user - which is an array
  • Retrieve data one by one as the user advances on the next issue - this is one information per call

API Examples

// Fetch all the data at once
app.get(‘/api/questions’, (req, res, next) => {
  Question.find({}, (err, questions) => {
    res.json(questions);
  });
});

// Fetch the data one by one
app.get('/api/questions/:id', (req, res, next) => {
  Question.findOne({ _id: req.params.id }, (err, question) => {
   res.json(question);
  });
});

1 , , , 200 , , mongodb , ,

2, , , api , mongodb .

Mongoose

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const QuestionSchema = new Schema({
    question: String,
    choice_1: String,
    choice_2: String,
    choice_3: String,
    choice_4: String,
    answer: String
});
+4
4

. , .

500 , 500 api. . , , .

, . 10 , 8- , 10 .

, . .

pageSize , - .

myquestionbank.com/api/questions?pageNumber=10&pageSize=2

var pageOptions = {
    pageNumber: req.query.pageNumber || 0,
    pageSize: req.query.pageSize || 10
}

.

Question.find()
    .skip(pageOptions.pageNumber * pageOptions.pageSize)
    .limit(pageOptions.pageOptions)
    .exec(function (err, questions) {
        if(err) {
        res.status(500).json(err); return; 
        };

        res.status(200).json(questions);
    })

: (0), , .

skip() n . , pageNumber , (pageOptions.pageNumber * pageOptions.pageSize) , - . (pageNumber = 1) 10, 10 , .

limit() , .

, pageNumber . ( , )

, , , - , 10 (pageSize) , .

: .

+1

, . , . , , , , index. :

index = 0
questions = []

, , , 10 (. , MongoDB ), . questions [index] . 8 (= 9- ), 10 API . , , .

+1

mongodb.

api, = 20 skip = 0 , api.

1- = > limit = 20, skip = 0

next = > limit = 20, skip = 20 ..

app.get(‘/api/questions’, (req, res, next) => {
  Question.find({},{},{limit:20,skip:0}, (err, questions) => {
    res.json(questions);
  });
});
0

, - never-to-use, . , . , , api:

app.get(‘/api/questions/getOneRandom’, (req, res, next) => {
    Question.count({}, function( err, count){
        console.log( "Number of questions:", count );
        var random = Math.ceil(Math.random() * count);
        // random now contains a simple var
        now you can do
        Question.find({},{},{limit:1,skip:random}, (err, questions) => {
            res.json(questions);
        });
    })

});

skip:random , , . , . , , , .

, :)

0

Source: https://habr.com/ru/post/1672664/


All Articles