Print BSON of MongoDB with several different structures

0

Hello,

I'm making an application using Python (Flask) and MongoDB. In this application the user can assemble his page inserting Images, Text or youtube link. With the sequence you want.

This first part I did and I'm recording in Mongo. The problem is when it is time to return these data, since each document has a structure different from the other, as below:

Example 1:

    {
    "_id": {
        "$oid": "5afb6dbaee348620405e9844"
    },
    "texto1": "Lorem ipsum dolor sit amet",
    "texto2": "Lorem ipsum dolor ",
    "url_video1": "https://youtu.be/5b_eM9ee",
    "img1": "imagem_01.jpg",
    "url_video2": "https://youtu.be/5b_eM9lGPP8"
    "texto3": "Lorem ipsum dolor sit amet, consectetur",
    "img2": "imagem_02.jpg" 
}

Example 2:

    {
    "_id": {
        "$oid": "ee4243g55676j87875afb6dba"
    },
    "texto1": "Lorem ipsum dolor sit amet",
    "url_video1": "https://youtu.be/5b_eM9ee",
    "img1": "imagem_01.jpg",
    "texto2": "Lorem ipsum dolor ",
    "img2": "imagem_02.jpg",        
    "url_video2": "https://youtu.be/5b_eM9lGPP8",
    "texto3": "Lorem ipsum dolor sit amet, consectetur"        
}

I can bring all BSON, and play in HTML, the problem is that I'm not sure how to insert each item into the corresponding HTML : When is text ?? in a <textarea> , when it is img ?? in a <img> and so on, to mount the page in the sequence that the user created.

Maybe I need to work with BSON with JavaScript? What is the best solution?

Thank you for your attention!

    
asked by anonymous 23.08.2018 / 00:03

1 answer

1

Both JSON and its "brother", the BSON, do not preserve the order of the keys inside the document. The simplest solution is to store them inside an array , something like this:

{
    "_id" : { ... },
    "media": [
        { "type": "text", "content": "...", },
        { "type": "video", "url": "https://www.youtube.com/" },
        { "type": "image", "filename": "image.jpeg" },
     ]
 }

Incidentally the suggestion of type keys to identify the type of the document is optional, but I think it will help you to do a simpler routine to know what is stored in each array .

    
23.08.2018 / 03:58