【问题标题】:How do i design a json result in mongoose?我如何在猫鼬中设计一个 json 结果?
【发布时间】:2017-08-09 23:12:29
【问题描述】:

我的目标很简单,我想把这个特定的 json 结果设计成 mongoose 数据结构。

Json 示例

{  
         "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"
      },

我的目标是将这个 json 设计转换为猫鼬设计,以及我迄今为止的尝试。

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

那么稍后,在创建问题的过程中,如何将其中一个选项分配给 answer 属性?

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?

【问题讨论】:

  • 那么问题出在哪里?
  • 您在执行此操作时是否遇到任何错误?这里真正的问题是什么,请编辑您的问题以使其更易于理解。
  • @NenadVracar 我已经更新了问题

标签: node.js mongodb mongoose


【解决方案1】:

您的示例通过其属性名称引用答案,因此:

question.answer = 'choice_3';

稍后,在运行查询以检索问题后,您可以使用 .answer 的值将其转换回实际文本(用于显示目的):

let answer = question[question.answer];

【讨论】:

猜你喜欢
  • 2017-05-08
  • 2021-12-21
  • 2018-08-23
  • 2018-08-22
  • 2022-01-23
  • 2016-07-30
  • 2018-02-05
  • 2021-05-12
  • 2014-12-09
相关资源
最近更新 更多