0

A friend recently showed me that you can create an instance that is a subclass of dict in Python, and then use that instance to save, update, etc. Seems like you have more control, and it looks easier as well.

class Marker(dict):

  def __init__(self, username, email=None):
      self.username = username
      if email:
         self.email = email
  @property
  def username(self):
      return self.get('username')
  @username.setter
  def username(self, val):
      self['username'] = val
  def save(self):
      db.collection.save(self)
rjr862
  • 51
  • 5

1 Answers1

1

Author here. The general reason you'd want to use it (or one of the many similar libraries) is for safety. When you assign a value to a MongoAlchemy Document it does a check a check to make sure all of the constraints you specified are satisfied (e.g. type, lengths of strings, numeric bounds).

It also has a query DSL that can be more pleasant to use than the json-like built in syntax. Here's an example from the docs:

>>> query = session.query(BloodDonor)
>>> for donor in query.filter(BloodDonor.first_name == 'Jeff', BloodDonor.age < 30):
>>>    print donor
Jeff Jenkins (male; Age: 28; Type: O+)

The MongoAlchemy Session object also allows you to simulate transactions:

with session:
    do_stuff()
    session.insert(doc1)
    do_more_stuff()
    session.insert(doc2)
    do_even_more_stuff()
    session.insert(doc3)
    # note that at this point nothing has been inserted
# now things are inserted

This doesn't mean that these inserts are one atomic operation—or even that all of the write will succeed—but it does mean that if your application has errors in the "do_stuff" functions that you won't have done half of the inserts. So it prevents a specific and reasonably common type of error

Jeff Jenkins
  • 158
  • 1
  • 3