我是nodejs和mongoDB的新手,谁能帮我解决这个问题。我曾经使用multer、multer-gridfs-storage、gridfs-stream来上传文件和图像。但是我得到了这个TypeError: mongodb_1.ObjectID is not a constructor in resolve() 在 GridFsStorage 的承诺中。我已经分享了下面的代码。
const express = require('express');
const app = express();
require('dotenv').config()
const PORT = process.env.PORT;
const morgan = require('morgan');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const path = require('path');
const crypto = require('crypto');
const MongoURI = "atlas url";
app.use(methodOverride('_method'));
app.use(express.json())
app.use(morgan(':method :status :url'));
const connectDB = mongoose.createConnection(MongoURI,{useUnifiedTopology:true,useFindAndModify:false, useNewUrlParser:true,useCreateIndex: true})
let gfs;
connectDB.once('open',()=>{
console.log("dbConnected....")
gfs = Grid(connectDB.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)=>{
console.log("buf",buf)
if(err){
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
console.log("filename",filename)
const fileInfo = {
filename:filename,
bucketName:'uploads'
};
resolve(fileInfo)
})
})
}
})
app.listen(PORT,()=>{
console.log(`port connected....${PORT}`)
})
const upload = multer({storage:storage})
app.post('/uploadfile',upload.single('file'),async(req,res)=>{
res.json({
file:req.file
})
})