0

I'm new to MongoDB and MongoEngine and currently my documents are of below type :

[
    {
        "Question1": "How do you rate the whole restaurant",
        "Rating": [
            "Poor",
            "Average",
            "Good"
        ],
        "next": [
            {
                "Question2": "How do you rate food plates cleanness",
                "Rating": [
                    "Poor",
                    "Average",
                    "Good"
                ]
            },
            {
                "Question3": "How do you rate floor cleanness",
                "Rating": [
                    "Poor",
                    "Average",
                    "Good"
                ]
            }
        ]
    },
    {
        "Question4": "How do you rate food taste",
        "Rating": [
            "Poor",
            "Average",
            "Good"
        ]
    }
]

I'm thinking to create models in below manner in mongoengine:

class Ratings(db.EmbeddedDocument):
    Rating = db.ListField()

class Questions(db.EmbeddedDocument):
    Question = db.StringField()
    rating_type = db.EmbeddedDocumentField(Ratings)

class FeedbackFormTemplate(db.Document):
    pass

The above classes (Questions and Ratings) will be used to create questions and ratings.

I want to use the class: FeedbackFormTemplate to create the documents. But I'm not getting any ideas on building the models.

Any help on this is much appreciated.

1 Answers1

0

If you aren't bound to the shape of the schema you mentioned above, I'd recommend the following:

class QuestionDefinition(EmbeddedDocument):
    question = StringField()
    ratings = ListField(StringField(), default=["Poor", "Average", "Good"])
    next_questions = EmbeddedDocumentListField("self")

class FeedbackFormTemplate(Document):
    questions = EmbeddedDocumentListField(QuestionDefinition)

q1 = QuestionDefinition(question='Food good?')
q2 = QuestionDefinition(question='Plates cleanness?')
q1.next_questions = [q2]

q3 = QuestionDefinition(question='food taste?', ratings=['bad', 'terrible'])
FeedbackFormTemplate(questions=[q1, q3]).save()

print(FeedbackFormTemplate.objects.as_pymongo().first())    # print raw object as stored in mongo

Which would store the following in mongo:

{  
   '_id':ObjectId('5cfd5c49caf5e58c7b22f4a8'),
   'questions':[  
      {  
         'question': 'Food good?',
         'ratings': ['Poor', 'Average', 'Good'],
         'next_questions':[  
            {  
               'question': 'Plates cleanness?',
               'ratings': ['Poor', 'Average', 'Good'],
               'next_questions':[]
            }
         ]
      },
      {  
         'question': 'food taste?',
         'ratings': ['bad', 'terrible'],
         'next_questions': []
      }
   ]
}
bagerard
  • 5,681
  • 3
  • 24
  • 48