Kyaw Min Kyaw Min - 7 months ago 52
Node.js Question

multi upload to mongodb gfs"/", upload.single("avatar"), function(req, res, next){
var writestream = gfs.createWriteStream({
filename: req.file.filename
fs.createReadStream("./uploads/kkm/" + req.file.filename)
.on("end", function() {
fs.unlink("./uploads/kkm/"+ req.file.filename, function(err) {

I want to upload 2 images to mongodb, I can create write and read streams for one image but lost idea for two files.

I can pipe for one image but not two. When I try array medthod, it replys

"TypeError: Cannot read property 'filename' of undefined" ERROR.

My goal is to upload two files to mongodb in one method or what ever at once. How can I achieve this?


The GridFS methods insert one file per call but you can easily achieve that. You need to use loop in your Node.JS application and send the file one by one to GridFS.

if you use multer you can do something like this

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, './.temp/uploads');
    filename: (req, file, callback) => {
        callback(null, file.fieldname + '-' +;
const multerOptions = {
    storage: storage

const upload = multer(multerOptions).array('files[]');

module.exports = (req, res, next) => {
  upload(req, res, (err) => {
        for (let i in req.files) {
            const file = req.files[i];
            // here you can call GridFS method and upload the file