Exploring the capabilities of reading and showcasing images stored in mongoDB through the utilization of Grid

I have successfully managed to upload images to my mongoDB using GridFs. Here are some of the images stored in my database:

https://i.sstatic.net/QNdM5.png

fs.files:

https://i.sstatic.net/mDYSz.png

fs.chunks:

https://i.sstatic.net/0K1yJ.png

Provided below is the code I utilized for uploading these images:

var Grid = require('gridfs-stream');
var mongoose = require("mongoose");
Grid.mongo = mongoose.mongo;
var gfs = new Grid(mongoose.connection.db);

app.post('/picture', function(req, res) {
 var part = req.files.filefield;

            var writeStream = gfs.createWriteStream({
                filename: part.name,
                mode: 'w',
                content_type:part.mimetype
            });


            writeStream.on('close', function() {
                 return res.status(200).send({
                    message: 'Success'
                });
            });

            writeStream.write(part.name);

            writeStream.end();
   });

The Dilemma:

I am encountering difficulty in reading and displaying these images from mongoDB on the frontend within an HTML <img> tag.

My attempts so far have only resulted in displaying the file name:

app.get('/picture', function(req, res) {


gfs.files.find({ filename: 'trooper.jpeg' }).toArray(function (err, files) {

    if(files.length===0){
        return res.status(400).send({
            message: 'File not found'
        });
    }

    res.writeHead(200, {'Content-Type': files[0].contentType});

    var readstream = gfs.createReadStream({
          filename: files[0].filename
    });

    readstream.on('data', function(chunk) {
        res.write(chunk);
    });

    readstream.on('end', function() {
        res.end();        
    });

    readstream.on('error', function (err) {
      console.log('An error occurred!', err);
      throw err;
    });
  });
});

The above code snippet was referenced from here

Any assistance would be greatly appreciated as I have been struggling with this issue for quite some time now!

Answer №1

It needs to be

writeStream.write(part.data);

rather than

writeStream.write(part.name);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

MongoDB and Deployd are two important tools that work seamlessly

Currently experimenting with Deployd using MongoDB and an AngularJS front end on my Mac. I can successfully launch Node and Mongo, but it requires using the --config flag to start mongod. I have created a .conf file and launch it with the flag, specifying ...

Where can I locate the transparent background in an image?

I am facing a challenge in my HTML code where I need to position text within the transparent background of an image. I have been trying to figure out the exact coordinates dynamically using JS or HTML, but so far, I haven't had much success. My initia ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

Need to send emails to two separate users? Look no further than Resend.com for a quick and

I am currently utilizing resend.com to send an email containing different variables to two distinct users. import type { NextApiRequest, NextApiResponse } from "next"; import { EmailTemplate } from "../../components/emails/EmailTemplate" ...

If the <span> element contains text, then apply a class to the <i> element

Is there a way to target a different i element with the id 'partnered' and add the class 'checkmark'? $(document).ready(function () { jQuery('span:contains("true")').addClass('checkmark'); }); The current code su ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Experiencing difficulty in removing a row from an HTML table using jQuery DataTables

I have an HTML table populated with data from the database. My goal is to be able to delete a row from the HTML table without affecting the actual data in the database. Each row in the table has a delete button in the action column, and when clicked, tha ...

Issues with File Upload using Vue.js and the Flask framework

I am encountering difficulties when trying to upload an image using FormData from Vue.js to my Python Flask backend. In my setup, I have a Node.js server that is responsible for handling Vue.js (Nuxt) in order to enable server-side rendering. The basic sta ...

The model in ThreeJS appears distorted due to the camera perspective

How can I ensure that the lines of the first extremity align exactly with the lines on the second extremity, even though the radius is the same for both? And what steps do I need to take to achieve this alignment? camera = new THREE.PerspectiveCamera(45, ...

Simplify your jQuery code

Does anyone have suggestions for optimizing my code to reduce its weight? var t; $(".sn-fresh").mouseenter(function() { $(".um-cat").hide(); clearTimeout(t); $("#ultra-menu, #um-fresh").fadeIn(600); }); $(".sn-salt").mouseenter(function() ...

What could be causing the React component to not render?

I am currently developing a React application and I need to place an order. To do so, I require a comprehensive list of all users and products available. The CreateOrder component is integral to this process as it contains two crucial variables in its stat ...

`The challenge of navigating within Material UI tabs in a React js project`

In my current project, I am utilizing React Js along with the Material UI Tabs component to switch between two different components. However, I have encountered an issue where when I navigate to Tab 2 or Tab 1 by clicking on them, the route changes and th ...

Issue with ThreeJS object's quaternion rotation deviating from expected axis rotation

I am currently working on a project where I need a 3D object to follow a specified path while always facing the direction in which it is moving. To achieve this, I have been using the following code snippet: fishObject.quaternion.setFromAxisAngle(axis, ra ...

Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

While attempting to retrieve information from an API using $.getJSON(), I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken for accessing additional pages. In the code snippet below, my i ...

``I am facing an issue where Angular fails to update a $scope variable after

I am experiencing an issue with my AngularJS script. I have created a website for my personal network where I can control bulbs. I access the site on both my computer and mobile device. When I turn on a bulb on my mobile phone, the light goes off. I can ...

Comparison between Filament Group's loadCSS and AJAX technologies

The loadCSS library developed by Filament Group is widely recognized as the standard for asynchronously loading CSS. Even Google recommends its use. However, instead of using this library, some suggest utilizing ajax to achieve the same result. For example ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

Utilize PHP and REGEX to extract a JavaScript variable value from a script

Having trouble opening a JavaScript file from PHP, extracting a JSON variable and converting it to a PHP array. Struggling to determine the correct regex pattern to use at the moment. // retrieving the JS file $file = file_get_contents ("http://pve.proxm ...

How to delete an element from an array with UnderscoreJS

Here's a scenario: var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]; I'm looking to delete the element with id value of 3 from this array. Is there a method to achieve this without using splice? Perhap ...