I want to be able to get a list or some sort of set of fields that are required by the document i've created. For instance, here is my document:
nickName = StringField(required=True)
password = StringField(required=True)
firstName = StringField()
lastName = StringField()
joinDate = DateTimeField(required=True)
lastVisited = DateTimeField(required=True)
subscriptions = DictField(field=ObjectIdField())
isActivated = BooleanField(default=True)
profileImage = FileField()
isModerator = BooleanField(default=False)
description = StringField()
location = GeoPointField()
email = EmailField()
settings = DictField()
^From this document I should receive:
["nickName","password","joinDate","lastVisited"]
as results for being required fields. Is this possible? If so, how can I achieve the desired result.
Thanks in advance!
Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.
While both PyMongo and MongoEngine do both return objects (which is not wrong), PyMongo returns dictionaries that need to have their keys referenced by string. MongoEngine allows you to define a schema via classes for your document data.
MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database.
This is what I wrote to generate a dict of all the fields and their nested types.
from mongoengine.fields import (
IntField,
BooleanField,
StringField,
DateTimeField,
DecimalField,
FloatField,
LongField,
ListField,
EmbeddedDocumentField,
ReferenceField,
)
__input_types = {
IntField,
BooleanField,
StringField,
DateTimeField,
DecimalField,
FloatField,
LongField,
}
__input_num_types = {
IntField,
BooleanField,
DecimalField,
FloatField,
LongField,
}
def list_schema(m):
"""list all the field in the model
and in the nested models"""
sdict = {}
for k, v in m._fields.iteritems():
if k == '_cls':
continue
ftype = type(v)
if ftype in __input_types:
sdict[k] = {
'default': v.default if v.default else '',
'is_num': ftype in __input_num_types,
'required': v.required,
}
elif ftype == ListField:
seqtype = v.field
if seqtype in __input_types:
sdict[k] = [{
'default': v.default() if v.default else '',
'is_num': seqtype in __input_num_types,
'required': v.required,
}]
else:
sdict[k] = [list_schema(seqtype.document_type)]
else:
sdict[k] = list_schema(v.document_type)
return sdict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With