I had this error while I am trying to use multer-gridfs-storage, I want to upload files and store them in mongoDB atlas
index.js file:
require("dotenv").config();
const upload = require("./routes/upload");`your text`
const Grid = require("gridfs-stream");
const mongoose = require("mongoose");
const connection = require("./db");
const express = require("express");
const app = express();
let gfs;
connection();
const conn = mongoose.connection;
conn.once("open", function () {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("photos");
});
app.use("/file", upload);
// media routes
app.get("/file/:filename", async (req, res) => {
try {
const file = await gfs.files.findOne({ filename: req.params.filename });
const readStream = gfs.createReadStream(file.filename);
readStream.pipe(res);
} catch (error) {
res.send("not found");
}
});
app.delete("/file/:filename", async (req, res) => {
try {
await gfs.files.deleteOne({ filename: req.params.filename });
res.send("success");
} catch (error) {
console.log(error);
res.send("An error occured.");
}
});
const port = process.env.PORT || 5666;
app.listen(5000, console.log(`Listening on port ${port}...`));
db.js file
const mongoose = require("mongoose");
module.exports = async function connection() {
try {
await mongoose.connect(
"mongodb+srv://gmcws2024:[email protected]/camping-app?retryWrites=true&w=majority"
);
console.log("connected to database");
} catch (error) {
console.log(error);
console.log("could not connect to database");
}
};`
**upload.js middleware**
`const multer = require("multer");
const GridFsStorage = require("multer-gridfs-storage");
const storage = new GridFsStorage({
url: "mongodb+srv://gmcws2024:[email protected]/camping-app?retryWrites=true&w=majority",
file: (req, file) => {
const match = ["image/png", "image/jpeg"];
if (match.indexOf(file.mimetype) === -1) {
const filename = `${Date.now()}-any-name-${file.originalname}`;
return filename;
}
return {
bucketName: "photos",
filename: `${Date.now()}-any-name-${file.originalname}`,
};
},
});
module.exports = multer({ storage });
upload route
const upload = require("../middleware/upload");
const express = require("express");
const router = express.Router();
router.post("/upload", upload.single("file"), async (req, res) => {
if (req.file === undefined) return res.send("you must select a file.");
const imgUrl = `${req.protocol}://${req.headers.host}/file/${req.file.filename}`;
return res.send(imgUrl);
});
module.exports = router;
package.json file
{
"name": "nouveau-dossier",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2",
"gridfs-stream": "^1.1.1",
"mongoose": "^8.0.3",
"multer": "^1.4.4",
"multer-gridfs-storage": "^4.2.0",
"nodemon": "^3.0.2"
}
}
but this error accured : "Error: The database connection must be open to store files
at GridFSStorage._handleFile (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\multer-gridfs-storage\lib\gridfs.js:321:6)
at C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\multer\lib\make-middleware.js:145:17
at allowAll (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\multer\index.js:8:3)
at wrappedFileFilter (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\multer\index.js:44:7)
at Busboy. (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\multer\lib\make-middleware.js:115:7)
at Busboy.emit (node:events:514:28)
at Busboy.emit (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\busboy\lib\main.js:38:33)
at PartStream. (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\busboy\lib\types\multipart.js:213:13)
at PartStream.emit (node:events:514:28)
at HeaderParser. (C:\Users\MOHAMED ANWAR\Desktop\Nouveau dossier\node_modules\dicer\lib\Dicer.js:51:16)"