1

Sorry for such a basic question but I've really struggled to find a solution elsewhere online and I am trying to learn the MERN stack. I am trying to upload a file to mongodb and in my server.js file the following code uploads the file as expected. I can see the details of the file in the db. But when I try to move this into a route, so it is not in my server file, it fails. My main question is how can I take the following and add it to a router.post('/fileupload'...) as its own .js file in my routes folder so that it uploads to my db. Thanks!

var conn = mongoose.connection;
    if (conn !== "undefined") {
        var grid = require("gridfs-stream");
        var fs = require("fs");
        grid.mongo = mongoose.mongo;
        conn.once("open", () => {
            console.log("conn open");
            var gridfs = grid(conn.db);
            var streamwrite = gridfs.createWriteStream({
                filename: "tmp.txt"
            });
            fs.createReadStream("tmp2.txt").pipe(streamwrite);
            streamwrite.on("close", function (file) {
                console.log("Write written successfully in database");
            });
        });
    } else {
        console.log('sorry not connected');
    }

How I access the route from my server.js:

const fileupload = require("./routes/api/fileupload");
app.use("/api/fileupload", fileupload)
Aaron Rotem
  • 356
  • 1
  • 3
  • 18

1 Answers1

2

You can do something like this -

uploadRoute.js


// Config
const config = require('../../../config/config');

// Logic
const mongoose = require("mongoose");
const fs = require('fs');
const Grid = require('gridfs-stream');

//models
const Files = require('../../../models/files.model');

module.exports = router => {
    const conn = mongoose.connection;
    Grid.mongo = mongoose.mongo;
    let gfs;

    conn.once("open", () => {
        gfs = Grid(conn.db);

        router.post('/bucket/upload', (req, res) => {
            let {
                file
            } = req.files;
            let writeStream = gfs.createWriteStream({
                filename: `${file.name}`,
                mode: 'w',
                content_type: file.mimetype
            });
            writeStream.on('close', function (uploadedFile) {
                Files.create({
                        doc_id: uploadedFile._id,
                        length: uploadedFile.length,
                        name: uploadedFile.filename,
                        type: uploadedFile.contentType
                    })
                    .then(file => res.json({
                        success: true,
                        message: "File was saved with success"
                    }))
                    .catch(err => {
                        console.error(`[*] Error, while uploading new files, with error: ${err}`);
                        res.status(500).json({
                            message: `[*] Error while uploading new files, with error: ${err}`
                        })
                    })
            });
            writeStream.write(file.data);
            writeStream.end();
        });
    });
}

For gridfs you need to provide a model in mongo to store data, you can give blank model or add some custom fields which will be part of mongo collection with some additional fields which gridfs adds.

models.js


const mongoose = require('mongoose');

const fileSchema = new mongoose.Schema({
    doc_id: {
        type: String
    },
    length : {
        type: Number
    },
    name: {
        type: String
    },
    type: {
        type: String
    }
});

module.exports = mongoose.model('File', fileSchema);

shiva2492
  • 409
  • 3
  • 10