0

I am trying to make simple rating application, where I am using MongoDB via MongoEngine ODM. I have some troubles with understanding the ReferencingField(). I am tracking changes of User() documents with fields date_created and date_modified in User collection. Both should include the datetime and reference to user.

I solved the referencing via adding ObjectID to date_created and date_modified after first saving the User. Is it in the end same thing as using ReferenceField()? Is there more simpler way to archieve this? For example use ReferenceField() in the ModificationInformation() class?

My implementation is as follows:

class ModificationInformation(EmbeddedDocument):
    user = ObjectIdField()
    date = DateTimeField(default=datetime.datetime.utcnow)

class User(Document):
    username = StringField()
    first_name = StringField()
    last_name = StringField()
    date_created = EmbeddedDocumentField(ModificationInformation)
    date_modified = EmbeddedDocumentListField(ModificationInformation)

# Create user
user_1 = User(
    username = "jodo",
    first_name = "John",
    last_name = "Doe"        
    )

user_1.save()

user_1.date_created = ModificationInformation(user = user_1.id)
user_1.date_modified = [ModificationInformation(user = user_1.id)]

user_1.save()
LauriTK
  • 1
  • 2
  • It seems like you are trying to reference the User in an embedded user document. That doesn't seem necessary. Embedded documents are always attached to the parent document. Are you giving other users the ability to modify other users' information? I can show you how to use the ReferenceField, but I want to be clear that this is the information that you want. If a user modifies there own information this may cause an infinite loop or an error. – Joseph Vargas Jul 21 '18 at 12:34
  • Yes, that was my intention. Mainly administrators/moderators can modify other users profiles. The ModificationInformation() is also used in other classes. Recursive to infinity / error is indeed a problem. Thank you, I would love to hear your suggestions :). – LauriTK Jul 21 '18 at 13:51
  • I would have stored the user id in the ModInfo Document as a StringField, and later dereferenced it by using bson.ObjectID("someID") but it seems as though your method is working about the same. Sorry I don't think I can offer a more convienient solution. – Joseph Vargas Jul 21 '18 at 17:27

0 Answers0