bradtraversy / mongo_file_uploads Goto Github PK
View Code? Open in Web Editor NEWExample of uploading files to a MongoDB database
Example of uploading files to a MongoDB database
Hi, I followed the code and was able to successfully upload files onto MongoDB with GridFsStorage. However, my GET functions to retrieve files run into errors: "can't read property 'files' of undefined"
I've tried debugging where gfs was initialized but I'm unsure where the problem is.
const conn = mongoose.createConnection(mongoURI);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
console.log("Connected to DB");
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
Somehow my gfs is undefined after initializing. I'm using mongoose 5.12.5, express 4.17.1, gridfs-stream 1.1.1, for reference.
UnhandledPromiseRejectionWarning : failed to connect to server
MongoNetworjError : getaddrinfo ENOTFOUND
If the image is deleted the uploads.files document of that image get deleted. But the image in uploads.chunks document is not getting deleted.
when I enter this address "http://localhost:5000/files" in my browser, I get this response "no file exists" where that file is already uploaded in database but I don't know why is this showing.
got an error when i changed mongoose.createConnection with mongoose.connect.
gfs.files.find & gfs.files.findOne is always returning null. I've double checked inside of my db and the uploads.files is there with a file inside it. I'm assuming that something is deprecated. I just can't find where the issue is.
Hi Brad,
Many thanks for this tutorial.
I just have realized that the line 127 in "app.js" file is:
if (file.contentType === 'image/jpeg' || file.contentType === 'img/png') {
should be fixed to:
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
The type is "image/png" and not "img/png"otherwise it will not show the PNG type images after upload.
Thanks
mongo.connection.js
const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
let gfs;
const establishConnection = async () => {
try {
mongoose.set("strictQuery", false);
await mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const connect = mongoose.connection;
connect.on("error", (err) => {
console.error("Mongoose connection error:", err);
});
connect.once("open", () => {
gfs = new mongoose.mongo.GridFSBucket(connect.db, { bucketName: "uploads" });
console.log("Mongoose connection successful.");
});
} catch (err) {
console.error("Mongoose connection error:", err);
throw err;
}
};
const getGfsInstance = () => {
if (!gfs) {
throw new Error("Connection not established. Call establishConnection first.");
}
return gfs;
};
module.exports = { establishConnection, getGfsInstance };
user.controller.js
const { gfs } = require("../connnection/mongo.connection");
exports.postRetriveAll = async (res, req) => {
try {
// await establishConnection();
console.log("Retrieved gfs:", gfs);
// Retrieve all file details from the "uploads" bucket
gfs.find({}).toArray((err, files) => {
if (err) {
console.error("Error:", err);
} else {
console.log("Files:", files);
}
});
}
catch (err) {
console.log(err);
return err;
}
};
Output
Mongoose connection successful.
Retrieved gfs: undefined
TypeError: Cannot read properties of undefined (reading 'find')
i have called establishConnection() function in app.js file initially and also called it once again in user.controller.js but it didn't worked i also used the promise method but it didn't work
Unable to Run this Code ,getting following error
> (node:19300) UnhandledPromiseRejectionWarning: Error: Username containing an unescaped at-sign
at parseConnectionString (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongodb/lib/url_parser.js:176:13)
at parseHandler (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongodb/lib/url_parser.js:119:14)
at module.exports (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongodb/lib/url_parser.js:25:12)
at Promise (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongoose/lib/connection.js:338:5)
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongoose/lib/connection.js:337:19)
at Mongoose.createConnection (/home/vijo/Music/MEAN/mongo_file_uploads-master/node_modules/mongoose/lib/index.js:167:17)
at Object.<anonymous> (/home/vijo/Music/MEAN/mongo_file_uploads-master/app.js:22:23)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
(node:19300) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19300) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
`const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const app = express();
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
const mongoURI = 'mongodb://v:v@[email protected]:11568/mongouploads';
const conn = mongoose.createConnection(mongoURI);
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
app.get('/', (req, res) => {
gfs.files.find().toArray((err, files) => {
if (!files || files.length === 0) {
res.render('index', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'image/jpeg' ||
file.contentType === 'image/png'
) {
file.isImage = true;
} else {
file.isImage = false;
}
});
res.render('index', { files: files });
}
});
});
app.post('/upload', upload.single('file'), (req, res) => {
res.redirect('/');
});
app.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
return res.json(files);
});
});
app.get('/files/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
return res.json(file);
});
});
app.get('/image/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
app.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
return res.status(404).json({ err: err });
}
res.redirect('/');
});
});
const port = 5000;
app.listen(port, () => console.log(Server started on port ${port}
));`
I pulled your repo on this tutorial and setup mlab for the db storage, I have an app already deployed and looking to use this tutorial to customise for uploading profile image. The issue is that your repo uploads perfectly, but when the same code is called from client sidewith Angular Framework using Auth.service with a post request /upload, the file comes pack undefined and file will not upload:
nothing happens and ive console logged inside the POST /upload with the req.file with that returning undefined.
Any idea's what I could be doing wrong?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.