Storing data in GridFS with MongoDB from an express buffer

Currently, I am attempting to save an Image file that I'm sending as multipart in my MongoDB utilizing GridFS. My approach involves using multer with the memoryStorage option.

let upload = multer({ storage:  multer.memoryStorage() }).single('imageFile');
app.use(upload);

When accessing the buffer inside the route, I use the following method:

let buffer: Buffer = req.file.buffer;

Thus far, saving this buffer to my MongoDB has been a challenge for me.

let writeStream = this.gfs.createWriteStream({
            mode: 'w',
            filename: 'Image',
            content_type: 'image/png'
        });
streamifier.createReadStream(buffer).pipe(writeStream);

The above snippet illustrates my attempt at saving the buffer in MongoDB.

Mongoose: fs.files.ensureIndex([ [ 'filename', 1 ] ], { w: 1 })
Mongoose: fs.chunks.ensureIndex([ [ 'files_id', 1 ], [ 'n', 1 ] ], { w: 1, unique: true })
Mongoose: fs.files.findOne({ _id: ObjectId("597089c973179c0138eef7ae") }, { w: 1, readPreference: 'primary' })

Despite the log generated by my MongoDB, nothing seems to be stored in the database.

If anyone has a solution to offer, I would greatly appreciate it. I have already attempted a troubleshooting step outlined in this source, but it did not produce the desired outcome for me.

Answer №1

It turns out that the issue was not with the code I initially shared. The code does function correctly, but it's important to ensure that your gfs is loaded with the MongoDB instance rather than the connection.

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

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Confused about the behavior of bgchaindb?

I recently dived into the world of bigchainDB by following a tutorial that can be found here. After setting up two nodes with both bighchainDB and mongoDB servers, and configuring node id and address for each, I successfully managed to create transactions ...

Top approach for Constructing Angular Front-End Forms with User Input

Greetings to all who happen upon this message, thank you for taking the time to potentially offer assistance! In my past experiences working with Wordpress (PHP), I utilized a plugin called Advanced Custom Fields from advancedcustomfields.com. This plugin ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

"Despite the null date in Node.js, the validation for expiration dates less than Date.now() is still being enforced

I am currently working on implementing validation for evaluating the finish status. However, my validation is encountering a problem with the "null" value of expiresAt. It should indicate that the evaluation has been successfully completed. The issue lie ...

Tips on preventing Realtime database onWrite trigger function callback from iterating through data that has been altered

I am currently developing a 1 vs 1 game matching system using a real-time database. The system works by creating a record in the users table when a user signs in. Once there are two players with a status of placeholder, a cloud function generates a gameInf ...

Is it possible to use wildcards in Socket.io rooms or namespaces?

The hierarchy I am working with is as follows: Store -> Manager -> Assistant In this setup, a Manager has access to everything that the Assistant sends, while the Assistant can only access what the Manager explicitly provides. My understanding is t ...

What techniques do you employ to monitor dynamic webhooks on Shopify?

Shopify provides a webhook API that allows you to listen to events, such as when a product is updated or deleted. I have the idea of creating an app where users can connect their Shopify store and import all products into my database. However, I also need ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

The use of await can only occur inside an async function

Can someone explain the proper placement of the async keyword for me? I've tried a few different spots, but keep encountering the same error. async addNewCategory() { let alert = this.alertCtrl.create({ title: 'New Category', ...

The hyperlink appears to be broken and isn't functional

On my website, I have a shared layout that is used across different pages. Within the layout.jade file, there is a link: a(href='../user/profile') Profile However, when on the page http://hello.com/member/list/profile, this link cannot redirec ...

When transferring the code to an exported function, it triggers a TypeError indicating a circular structure conversion issue when trying to convert

Experimenting with queries using the express and mysql packages, I encountered an issue when moving code to a different file for exporting. Initially, this code snippet worked without any problems: connection.connect(); connection.query('SELECT 1 + ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Struggling to retrieve object values through useContext? Consider implementing useReducer in conjunction with useContext for more efficient state management

I'm facing an issue while trying to access my dispatch functions and states from the useContext. Strangely, when I attempt to destructure the context object in order to access them directly, I receive an error message stating that it does not exist (E ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

Tips for showing a Dialog box in reference to multiple rows in a table

Objective: Retrieve data and showcase it in a dialog box using the button located in the Button column. Essentially, clicking on one of the buttons will display the corresponding data in the dialog. Challenge: Currently, I can only extract hardcoded s ...

What are the advantages of using any type in TypeScript?

We have a straightforward approach in TypeScript to perform a task: function identity(arg) { return arg; } This function takes a parameter and simply returns it, able to handle any type (integer, string, boolean, and more). Another way to declare thi ...

What could be the reason behind receiving a Req.Req (Nested request) when using this specific configuration in Express?

IMPORTANT NOTE: If you are experiencing issues with nested requests or responses, make sure to check the parameter order or utilize the express.router({mergeParams: true}) option. It seems like my requests are being encapsulated by an additional object re ...

Utilizing middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...