Print Mongodb BSON with several different structures

Asked

Viewed 68 times

0

I’m making an application using Python (Flask) and Mongodb. In this application the user can mount his page by inserting Images, Text or Youtube link. With the sequence you want.

This first part I did and I’m recording on Mongodb. The problem is time to return this data, because each document has a different structure than 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 the whole JSON, and play in HTML, the problem is that I’m not sure how to insert each item within the corresponding HTML: When is text?? in a <textarea>, when it is img?? in a <img> and so on, to assemble the page in the sequence that the user created.

I may have to work on the JSON javascript? What is the best solution?

1 answer

1

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

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

In fact the suggestion of the "type" keys to identify the document type is optional, but I believe it will help you to make a simpler routine to know what is stored in each element of the array.

  • Thanks for the comment. But still, I don’t see how to identify the sequence, the type of data I’m receiving. I will try using the array and do some tests. Thanks!

  • how do you create the data to send to the server? Attach another key there to tell the type of data. JSON stores data, but it has to have only a "photo" of the data itself - if you need more information about the data, for example, the type, you have to put more information in the json itself to describe it.

  • @jsbueno will work on this inclusion of a key at the time of generating the data using Angular, and with this key be able to identify the data. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.