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)