1

I currently have the following code, which saves the temp file to public/files I have tried to understand the MongoDB GridFS documentation but with no success.

I am wondering how do I get the files to save inside MongoDB GridFS instead of my public/file directory

I am aware I am missing the part where I need to send the uploaded file to mongodb - this is the part I don't know how to do.

In mongodb example they say to do something like:

fs.createReadStream('./myFile').pipe(
  bucket.openUploadStream('myFile', {
    chunkSizeBytes: 1048576,
    metadata: { field: 'myField', value: 'myValue' },
  })
);

however I am not using FS or do I need to upload the file to the temp and then do the fs

import formidable from 'formidable';
import { MongoClient, ObjectId } from 'mongodb';
var Grid = require('gridfs-stream');

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

export default async (req, res) => {
  const uri = process.env.MONGODB_URI;
  let client;
  let clientPromise;
  const options = {};
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
  const clients = await clientPromise;
  const database = clients.db('AdStitchr');
  var gfs = Grid(database, client);
  gfs.collection('uploads');

  const form = new formidable.IncomingForm();

  form.uploadDir = 'public/files';
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    var file = files.file;
    console.log(JSON.stringify(file));

    try {
      const newFile = File.create({
        name: `files\${file.newFilename}.mp3`,
      });
      res.status(200).json({ status: 'success' });
    } catch (error) {
      res.send(error);
    }
  });
};
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
Russell Harrower
  • 778
  • 1
  • 6
  • 20

0 Answers0