Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Document id by ReferenceField in mongoengine

In Mongoengine I'm trying to set the id field of a Document by a ReferenceField of a Document located in a different database.

class User(Document):
    name = StringField()
    meta = {"db_alias": "user_db"}

class Credential(Document):
    id = ReferenceField(User)
    password = StringField()
    meta = {"db_alias": "credentials_db"}

I can do stuff like u = User('someuser').save(), with the problem that Credential(u, 'somepassword').save() turns into

ValidationError (Credential:None) (Invalid Object ID: ['auto_id_0'] Field is required: ['id'])

Surely Mongodb only stores some ObjectIds and therefore I can't see why this should not be possible, but does MongoEngine support something like that?

like image 359
Martin Avatar asked Jun 30 '26 15:06

Martin


1 Answers

Document Ids must be unique so you need to set primary_key to True for the id field.

class Credential(Document):
    id = ReferenceField(User, primary_key=True)
    ...
like image 195
styvane Avatar answered Jul 03 '26 04:07

styvane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!