I am new to Python and MongoDB and I am struggling with how to set up my classes within my project to use MongoDB. In my learning journey I came across the mongoengine and I have the following question.
I have a project that has 1 database with currently 7 collections. The collections are:
cart
country
invoice
product
session
store
user
I am currently taking a long hard look at my collections and strongly considering eliminating the country and invoice collections. Country can be combined into both the store and user collection as individual fields. (Tax can still be figured based on where the sale is taking place… from the store country) I am unsure about the invoice collection as this can be a large collection over time. (having to keep sales records for long periods of time)
But upon looking up multiple questions I came across the mongoengine… From my research, it appears that mongoengine is a third party and if I am using pymongo it seems to not be required. Am I right?
My current classes are written like this:
from dataclasses import dataclass
from model.cart import Cart
@dataclass
class User(object):
def __init__(self, first_name, last_name, phone, email, uid, cart):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.email = email
self.uid = uid
self.cart = cart
def __getattr__(self, key):
return getattr(self, key)
def __repr__(self):
return "first_name: {}, last_name: {}, uid: {}, cart: {}, card: {}".format(self.first_name, self.last_name, self.uid, self.cart, )
first_name: str
last_name: str
phone: str
email: str
uid: str
cart: Cart
I find the documentation on mongoengine to define classes quite differently. They define classes like this:
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
I cannot find any documentation that tells me what format I need to use… Can you point me in the right direction for clarification? I am dying to read about this and whether I need to use the schema outlined in the mongoengine or if I can use the schema like all the tutorials explain in Python. I.E. can I use the standard class definition or do I need to use the mongoengine verison.
From what I can gather, the mongoengine version enforces validation. If I don’t use this format, I’m assuming I need to program in the validation. (the required portion and also max length, etc)
Am I on the right track?