Nextjs - Push files to mongodb (hexoid is not a function - error)

31 views Asked by At

I have created an API where I am taking file uploads from the web and pushing them to MongoDB. I am getting this error:

'hexoid is not a function.'

Can you tell me how to fix this? Can you provide a reference link or GitHub repo where files are being pushed to MongoDB?

Details are as follows:

route.ts

import { NextApiRequest, NextApiResponse } from 'next';
import { MongoClient, Binary } from 'mongodb';
import formidable from 'formidable';
import { promises as fs } from 'fs';
import { NextResponse } from 'next/server';

// MongoDB connection string and database information
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
const dbName = "test";
const collectionName = "resumes";

export const config = {
    api: {
        bodyParser: false,
    },
};

export async function POST(req: Request){
    if (req.method === 'POST') {
      const formidable = require('formidable');
      const form = new formidable.IncomingForm();

        form.parse(req, async (err: any, fields: any, files: { resume: any; }) => {
            if (err) {
                return NextResponse.json({ message: "Error parsing the form", error: err });
            }

            // Assume the file field is named 'resume'
            const file = files.resume;

            if (!file) {
               return NextResponse.json({ message: "No file uploaded" });
            }

            try {
                // Read the file content
                const fileContent = await fs.readFile(file.filepath);

                await client.connect();
                const db = client.db(dbName);
                const collection = db.collection(collectionName);

                // Insert the file into the database
                const result = await collection.insertOne({
                    filename: file.originalFilename,
                    contentType: file.mimetype,
                    file: new Binary(fileContent),
                });

                NextResponse.json({ message: "File uploaded successfully", result: result });
            } catch (error) {
                NextResponse.json({ message: "Error connecting to the database", error: error });
            } finally {
                await client.close();
            }
        });
    }
}

profile.tsx

const Profile = () => {

  // Handle file upload
  const handleFileUpload = async (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/api/uploadResume/route', {
        method: 'POST',
        body: formData,
      });
      const data = await response.json();
      console.log(data); // You can replace this with any action based on the response
      alert('Resume uploaded successfully');
    } catch (error) {
      console.error('Error uploading file:', error);
      alert('Error uploading resume');
    }
  };

  return (

Project structure:

enter image description here

0

There are 0 answers