2
votes

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?

1

1 Answers

3
votes

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)
    ...