我正在尝试从mongodb地图集中检索一个文件,我使用的是gridfsstream,multer.It一直给我这个错误。
TypeError: this.db.collection不是一个函数
我可以成功上传,但检索不是working.What,我在这里失踪了吗?
const router = require("express").Router();
const multer = require("multer");
const { mongo, connection } = require("mongoose");
const config = require("../../config/main").db;
const Grid = require("gridfs-stream");
Grid.mongo = mongo;
var gfs = Grid(config);
// set up connection to db for file storage
const storage = require("multer-gridfs-storage")({
url: config,
file: (req, file) => {
return {
filename: file.originalname
};
}
});
// sets file input to single file
const singleUpload = multer({ storage: storage }).single("file");
router.get("/files", (req, res) => {
gfs.files.find().toArray((err, files) => {
if (!files || files.length === 0) {
return res.status(404).json({
message: "Could not find files"
});
}
return res.json(files);
});发布于 2019-08-28 01:00:51
我希望还能帮助你,虽然过了几天!当我试图检索一个图像时,我也犯了同样的错误。下面是我的代码:
MongoClient.connect(config.Info.mongo_database, {}, (err, client) => {
if(err) { new Error("An error has occurred while this file is retrieving: "+ err); }
//throw the error: this.db.collection is not a function
let bucket = new mongo.GridFSBucket(client.db, {
bucketName: bucketName
});
bucket.openDownloadStreamByName(filename).pipe(response);
})我就这样解决了:
MongoClient.connect(config.Info.mongo_database, {}, (err, client) => {
if(err) { new Error("An error has occurred while this file is retrieving: "+ err); }
//Look this, I must to explicit database name, otherwise that error is thrown
let db = client.db('files_repository');
let bucket = new mongo.GridFSBucket(db, {
bucketName: bucketName
});
bucket.openDownloadStreamByName(filename).pipe(response);
})现在对我有用了!!
https://stackoverflow.com/questions/55766856
复制相似问题