0

I'm trying to upload images in my NodeJS app using GridFS and MongoDB. I want to compress the image before it is uploaded in MongoDB and I've shared the GridFS middleware.

I would like to know where I should put the compression code or if there is a better way to compress images?

require('dotenv').config();
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const Mongoose = require('mongoose');
const Mongouri = process.env.MONGO_URL;
let conn = Mongoose.connection;
let gfs;
conn.once('open',()=>{
    gfs = Grid(conn.db,Mongoose.mongo);
    gfs.collection('Posts');
});


//defining the middleware for multer so this will be called everytiime a new image is uploaded using multer 
let storage = new GridFsStorage({
    url:Mongouri,
    file:(req,file)=>{
        return new Promise(
            (resolve,reject)=>{
                const fileInfo = {
                    filename:Mongoose.Types.ObjectId()+file.originalname,
                    bucketName:"Posts"
                };
                resolve(fileInfo);
            }
        );
    }

});


//initialising multer with the middleware 
const upload = multer({storage});

module.exports = upload;
Théo Lavaux
  • 1,364
  • 3
  • 22
  • 46
impirios
  • 1
  • 4

1 Answers1

-1

Sharp is a better tool to compress the images before you save them in DB. Source - Sharp npm module

Ara Galstyan
  • 486
  • 1
  • 4
  • 11
  • Where do i include the sharp code like should i use it in the middleware itself or in the route – impirios Jan 05 '21 at 15:48
  • Can you please tell the best practise to compress images and store them in the Database? – impirios Jan 05 '21 at 16:18
  • Hi. This piece of code will help you to understand how to use it. Don't copy and paste it, as it will not gonna work. The purpose is to show how to use the Multer and Sharp modules to upload images to the DB. Here is the link to the code [pastebin link](https://pastebin.pl/view/28636842) – Ara Galstyan Jan 06 '21 at 15:29