0

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!

4

2 回答 2

1

You want an ObjectIdField: http://www.mongoalchemy.org/api/schema/fields.html#mongoalchemy.fields.ObjectIdField

This is the type of field which is used for mongo_id (although that one is special-cased)

于 2014-08-19T17:54:20.200 回答
0

try

id = db.ObjectIdField().gen()

This would automatically generate the object id for each instance of the mongo db object/document - as would id's in relational dbs

于 2020-04-23T12:54:43.630 回答