Last active
April 20, 2019 16:45
-
-
Save nitinbhojwani/93737ee6c4709c3be94bfdcf67829aa9 to your computer and use it in GitHub Desktop.
Mongoengine Add or Remove EmbeddedDocument in ListField of EmbeddedDocuments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# roles as Python list of dictionaries | |
roles = [ | |
{'org': 'ABC', 'permissions':['RO', 'RW']}, | |
{'org': 'DEF', 'permissions':['RO', 'RW']}, | |
{'org': 'GHI', 'permissions':['RO', 'RW']}, | |
{'org': 'JKL', 'permissions':['RO', 'RW']}, | |
] | |
# get user object | |
user = User.objects(id=ObjectId('user_id')).first() | |
# create an EmbeddedDocument of Role for each element and append to ListField | |
for role_dict in roles: | |
role = Role(**role_dict) | |
user.roles.append(role) | |
# Save the Mongo Document | |
user.save() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mongoengine import Document | |
from mongoengine import EmbeddedDocument | |
from mongoengine.fields import EmbeddedDocumentField | |
from mongoengine.fields import ListField | |
from mongoengine.fields import StringField | |
class User(Document): | |
roles = ListField(EmbeddedDocumentField(Role)) | |
class Role(EmbeddedDocument): | |
org_name = StringField() | |
permissions = ListField(StringField()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# orgs against which user's access to be removed. | |
orgs = ['ABC', 'JKL'] | |
# get user object | |
user = User.objects(id=ObjectId('user_id')).first() | |
# remove all the roles from user for which org "is in" orgs | |
user.update(pull__roles__org__in=orgs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment