문제

tl;dr Is my schema okay?

My resolution for this year is to learn something new, and I've chosen to learn something about non-rel databases, i.e. Mongo. I'm currently working on a simple app which uses mongo as the database engine.

The application I'm working on is a simple questionnaire app: admin creates question, (logged in) user answers them. So: User has many Answer belongs to Question. What would be the most appropriate schema for such an app? I created the next schema myself (pseudo), but I'm wondering if you have any hints/tips solving this.

users [
    {
        # some required fields to authenticate the user
        email: j.doe@example.com,
        password: ...
        etc.

        # next fields are this users answers to a question
        # the key is the question's id, it's value the answer
        1: 'John',
        2: 'Doe',
    },
]

questions [
    { # no 1 (I know id's in mongo aren't numbered this way,
      # this is just for the sake of readability.
        question: What is your first name?,
        type: open,
        required: true,
    },
    { # no 2
        question: What is your last name?,
        type: open,
        required: false,
    },
    # and so on.
]
도움이 되었습니까?

해결책

I'd move answers inside questions collection:

{_id: 1, 
 question: "?", 
 type: "open", 
 required: true, 
 answered: [
   {email: "j.doe@example.com", answer: "John"},
   {email: "bob@example.com", answer: "Bob"},
 ]
}

Also using dynamic fields (like answer IDs) will make you impossible to index them.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top