0

My goal is really simple, I want to design this particular json result into mongoose data structure.

Json example

{  
         "question": "Who was the 13th president of the United States?",
         "choice_1": "Millard Fillmore",
         "choice_2": "Zachary Taylor",
         "choice_3": "Franklin Pierce",
         "choice_4" :"James K. Polk",
         "answer" :"choice_1"
      },

My goal is to transform this json design into mongoose design, and my attempt so far.

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
});

So later on, during the creation of the question, how do I assign one of the choices to the answer attribute?

const Question = require('/question');

const question = new Question();
question.question = req.body.question;
question.choice_1 = req.body.choice_1;
question.choice_2 = req.body.choice_2;
question.choice_3 = req.body.choice_3;
question.choice_4 = req.body.choice_4;
question.answer = // how do i put choice 1 - 3 here?
airsoftFreak
  • 1,450
  • 5
  • 34
  • 64

1 Answers1

1

Your example refers to the answer by its property name, so:

question.answer = 'choice_3';

Later on, after running a query to retrieve a question, you can use the value of .answer to convert it back to the actual text (for display purposes):

let answer = question[question.answer];
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Hello robert I have this question that needs your help, since you are the expert in MongoDB http://stackoverflow.com/questions/42885278/should-i-return-an-array-or-data-one-by-one-in-mongoose/42885336#42885336 – airsoftFreak Mar 19 '17 at 10:36