Sunday 19 March 2017

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

I have this simple app that I created using IOS, it is a questionnaire app, whenever user clicks play, it will invoke a request to node.js/express server

enter image description here

enter image description here

Technically after a user clicks an answer it will go to the next question

enter image description here

I'm confused to use which method, to fetch the questions/question

  1. fetch all the data at once and present it to the user - which is an array
  2. Fetch the data one by one as user progress with the next question - which is one data 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);
  });
});

The problem with number 1 approach is that, let say there are 200 questions, wouldn’t it be slow for mongodb to fetch at once and possibly slow to do network request

The problem with number 2 approach, I just can’t imagine how to do this, because every question is independent and to trigger to next api call is just weird, unless there is a counter or a level in the question mongodb.

Just for the sake of clarity, this is the question database design in 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
});



via airsoftFreak

No comments:

Post a Comment