我收到以下错误。基本配置如下:我已经在服务器上上传了文件,我想下载它们,但是收到这些错误我调用了一个 POST 请求到 /api/files/delete/${fileId} 应该调用路由并返回文件到浏览器,而不是使用 Grid 相关模块获取错误。
MONGODB_CONNECTION_STRING = mongodb://localhost:27017/Cstore
Db structure={Cstore:{uploads.files,uploads.chunks,users}}
On requesting POST axios.post(`/api/files/delete/${fileId}`)
Getting error:
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
[0] ^
[0]
[0] TypeError: grid.mongo.GridStore is not a constructor
[0] at new GridReadStream (/home/lenovo/Desktop/react/cstore/node_modules/gridfs-stream/lib/readstream.js:68:17)
This is server.js
app.get('/image/:filename', (req, res) => {
gfs.files.findOne({
_id: mongoose.Types.ObjectId(req.params.filename)
// filename: req.params.filename.toString()
}, (err, file) => {
// Check if file
if (!file || file.length === 0) {
console.log("not found")
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
// Read output to browser
console.log(file)
let id=file._id;
const readStream = gfs.createReadStream(
{
_id: mongoose.Types.ObjectId(req.params.filename)
}
// {
// _id: id
// }
)
readStream.on('error', err => {
// report stream error
console.log(err);
});
// the response will be the file itself.
readStream.pipe(res);
// let readstream = gfs.createReadStream(mongoose.Types.ObjectId(file._id))
// readstream.pipe(res)
// } else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
mongoose.Promise = global.Promise;
mongoose.connect(
mongoURI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) throw err;
console.log('MongoDB connection established');
}
)
const connection = mongoose.connection;
/// HANDLING FILE
let gfs;
connection.once('open', () => {
// Init stream
gfs = Grid(connection.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 = file.originalname;
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
})
const upload = multer({ storage });
Initial:
const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const path = require('path');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override')
const crypto = require('crypto')
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(cookieParser());
const dotenv=require('dotenv');
dotenv.config({path:__dirname+'/.env'});
const mongoURI = process.env.MONGODB_CONNECTION_STRING