I am setting up an up/download and have used several resources. I need to be able to store the "files" in the Mongo datastore and then read them back out. I was able to upload, but downloading is through an error when I try to instantiate the createReadStream.
I have over come most of the other errors in the original code. Here is my Package.json:
{
"name": "downloadtest",
"version": "2.3.0",
"license": "MIT",
"scripts": {
},
"engines": {
"node": "6.11.1",
"npm": "3.10.9"
},
"private": true,
"dependencies": {
"body-parser": "^1.19.0",
"core-js": "3.1.3",
"express": "^4.17.1",
"gridfs-stream": "^1.1.1",
"mongoose": "^5.6.7",
"mongoose-unique-validator": "^2.0.3",
"multer": "^1.4.2",
"multer-gridfs-storage": "^3.3.0",
"path": "^0.12.7",
},
"devDependencies": {
}
}
Here is the code that is throwing the error:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
mongoose.connect(mongoURI, { useNewUrlParser: true });
let conn = mongoose.connection;
let multer = require('multer');
let GridFsStorage = require('multer-gridfs-storage');
let Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
let gfs = Grid(conn, mongoURI);
let port = 3000;
// Setting up the root route
app.get('/', (req, res) => {
res.send('Welcome to the express server');
});
// Allows cross-origin domains to access this API
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin' , 'http://localhost:4200');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append("Access-Control-Allow-Headers", "Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.append('Access-Control-Allow-Credentials', true);
next();
});
// BodyParser middleware
app.use(bodyParser.json());
// Setting up the storage element
let storage = GridFsStorage({
gfs : gfs,
url: mongoURI,
options: {
useNewUrlParser: true
},
filename: (req, file, cb) => {
let date = Date.now();
// The way you want to store your file in database
cb(null, file.fieldname + '-' + date + '.');
},
// Additional Meta-data that you want to store
metadata: function(req, file, cb) {
cb(null, { originalname: file.originalname });
},
root: 'fs', //root name for collection to store files into
curCol: 'fs'
});
// Multer configuration for single file uploads
let upload = multer({
storage: storage
}).single('file');
// Route for file upload
app.post('/upload', (req, res) => {
upload(req,res, (err) => {
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0, error_desc: null, file_uploaded: true});
});
});
// Downloading a single file
app.get('/image/:filename', (req, res) => {
console.log('Searching for: '+ req.params.filename);
gfs.collection('fs'); //set collection name to lookup into
/** First check if file exists */
gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
if(!files || files.length === 0){
return res.status(404).json({
responseCode: 1,
responseMessage: "error"
});
}
// create read stream
console.log('Found: ' + files[0].filename)
// console.dir(gfs);
console.dir(files[0])
var readstream = gfs.createReadStream({
filename: files[0].filename,
root: "fs"
});
// // set the proper content type
// res.set('Content-Type', files[0].contentType)
// // Return response
// return readstream.pipe(res);
});
});
app.listen(port, (req, res) => {
console.log("Server started on port: " + port);
});
Finally, here is the error being thrown:
Server started on port: 3000
Searching for: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
Found: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
{ _id:
ObjectID {
_bsontype: 'ObjectID',
id:
Buffer [Uint8Array] [ 90, 104, 195, 29, 197, 30, 94, 0, 20, 99, 208, 206 ] },
filename: 'd47e793f3f5492b4e55869d167a471f5_imageThumb.png',
contentType: 'binary/octet-stream',
length: 13031,
chunkSize: 261120,
uploadDate: 2018-01-24T17:32:14.048Z,
aliases: null,
metadata: null,
md5: '5b314153a6bb0004329ccd1fcf8e037e' }
C:\Users\user\Desktop\downloadtest\node_modules\mongodb\lib\utils.js:132
throw err;
^
TypeError: grid.mongo.ObjectID is not a constructor
I've found a couple of references, but nothing seems to relate. To help troubleshoot, I've put in a couple of console logs and a DIR. I am hitting the DB, I am getting the document.. I just cannot start the read stream.