How to convert Python mongongine object (Document) to dictionary?

Question:

I have a collection of object stored in mongo which I retrieve with python mongoengine. I wish to return a lit of these object in json format to an http request but it seems IMPOSSIBLE to do. This is the piece of code where I want to return the dictionaries

        products = ProductModel.objects()
        products_dict = {}
        try:
            for index, product in enumerate(products):
                products_dict[f"product_{index}"] = product.to_dict()
        except StopIteration:
            pass
        finally:
            return jsonify(products_dict), HTTPStatus.OK

and this is my document class:

from flask_mongoengine import Document
from mongoengine.fields import (
    StringField,
    DateTimeField,
    FloatField,
    IntField,
)


class ProductModel(Document):
    product_id = StringField(db_field="productId", unique=True)
    product_name = StringField(db_field="productName")
    price = FloatField(db_field="price")
    stock = IntField(db_field="stock")
    description = StringField(db_field="description", required=False)
    animal_type = StringField(db_field="animalType", required=False)
    expiration_date = DateTimeField(db_field="epirationDate", required=False)

    meta = {"indexes": [("product_id"), ("product_name")]}

I am sure it cant be that hard how can someone convert these objects to dictionaries I cant find anything in the documentation

Asked By: KZiovas

||

Answers:

Ok I found these two ways. Python objects made form a class inheriting from mongo Document, can be converted:

  1. to json type and then be used accordingly
  2. to SON type and then to dict
Answered By: KZiovas

You may use to_mongo()

products = ProductModel.objects()
products.to_mongo()

This will give you Python dict.

Answered By: Vitalii Mytenko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.