Is it possible to store a mongo_id as an ObjectId
object in a MongoAlchemy field? I've been able to store an ObjectId
inside of a document I defined manually, but it seems as though I'm restricted to storing the string value of the id in the context of the MongoAlchemy ORM.
Here's some of my code:
class Group(db.Document):
name = db.StringField()
trial_id = db.StringField(required=False)
participants = db.ListField(
db.DictField(db.AnythingField()), default_empty=True, required=False)
def add_participant(self, participant):
self.participants.append({
'participant_id': participant.mongo_id,
'start': datetime.utcnow(),
})
class Trial(db.Document):
name = db.StringField()
groups = db.ListField(
db.DocumentField(Group), default_empty=True, required=False)
def add_group(self, group):
group.trial_id = str(self.mongo_id)
group.save()
def get_group(self, group):
return Group.query.filter(
{'name': group, 'trial_id': str(self.mongo_id)}).first()
You'll see that I'm able to store a mongo_id as an ObjectId
object in the Group
method add_participant
(since it's creating document manually, not through the MongoAlchemy ORM), but am forced to convert the mongo_id to a string in order to store it in a db.StringField
.
I tried storing the original ObjectId
in a db.AnythingField
, but was then unable to filter by it.
Does anyone know if it's possible to store an ObjectId
in a MongoAlchemy field and then filter by it in a database query?
Thank you!