How to save an image in mongodb and use it later in my html

    <div class="card-body">
    <form action="/Data" method="post">
    <label for="titulo">Titulo:</label>
    <input type="text" name="titulo" id="titulo"class="form-control">

    <label for="descricao">Descrição:</label> 
    <input type="text" name="descricao" max="20" id="descricao"class="form-control">

    <label for="image">imagem:</label>
    <input type="file" name="image" id="image" class="form-control" accept="image/png,image/gif,image/jpg,image/jpeg">

    <label for="comentario">Texto:</label>
    <div class="form-floating">
         <textarea class="form-control" placeholder="Leave a comment here" id="comentario" name="comentario" style="height: 150px"></textarea>

    <button type="submit" class="btn btn-success mt-2">Cadastra postagem</button>

    const novaPostagem = {

  new Postagens(novaPostagem).save().then(()=>{
        console.log("salva com sucesso!!!")
        console.log("erro ao salva:"+err)

Good morning!

Try to see if this link helps you

what is this???i dont understand.

Sorry… This is the correct link

You can but I advise against it.

First let me tell you how to do it: images are binary data so you need to store it as binary array using dedicated data type called BinData.

Then after reading the document you have to deserialize that type to an array of bytes that can later be exposed using HTTP protocol and used in your HTML.

If for any reason you cannot use binary type, you can store it even as a plain text but before you do that, you have to encode binary data using base64 encoding. Then after reading the document additionally you have to decode it from base64 back to binary and expose the image using HTTP. Bare in mind that using base64 encoding unfortunately increases the size by ~33%.

Now let me tell you why it’s better not to store images in a database: this won’t scale well. If you want to store 100 images, that’s ok. But if you’re thinking about hundreds of thousands, it’s better to choose another solution.

First of all, you need to remember about the document size limits: 16MB, so large images won’t fit.

Secondly, even if your images are smaller than 16MB, they will still be large and will replicate slowly to the secondary nodes. Inserting large documents will take a long time, saturating the connection pool.

Thirdly, images are binary, json is text, and bson (that is, the form in which the json is stored on disk) is binary again. This means that the database will have to do extra work for multiple bin/text conversion.

There are better ways to store images on servers like: CDN or S3.