Error: The database connection must be open to store files

烂漫一生 提交于 2020-06-17 14:37:45

问题


I am using mongodb atlas to store my data in cloud but i am unable to store it as i am getting the same error continuously Error:The database connection must be open to store files

My server side code


const mongoURI = 'mongodb+srv://caman3874:qwertyuiopaman1234@@amanco-pexfz.mongodb.net/test?retryWrites=true&w=majority';



const conn = mongoose.createConnection(mongoURI,{useNewUrlParser:true});


let gfs;

conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('uploads');
  console.log("connection made successfully");
});


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)=>{
  res.render('index');
 });


app.post('/upload', upload.single('file'), (req, res) => {
   res.json({ file: req.file }); 
});
const port = 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

My html code

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
    crossorigin="anonymous">

  </style>
  <title>Mongo File Uploads</title>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 m-auto">
        <form action="/upload" method="POST" enctype="multipart/form-data">
          <div class="custom-file mb-3">
            <input type="file" name="file" id="file" class="custom-file-input">
            <label for="file" class="custom-file-label">Choose File</label>
          </div>
          <input type="submit" value="Submit" class="btn btn-primary btn-block">
        </form>
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
    crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
    crossorigin="anonymous"></script>
</body>

</html>

Error: The database connection must be open to store files at GridFSStorage._handleFile (C:\Users\91807\Desktop\mongo\node_modules\multer-gridfs-storage\lib\gridfs.js:339:17) at C:\Users\91807\Desktop\mongo\node_modules\multer\lib\make-middleware.js:144:17 at allowAll (C:\Users\91807\Desktop\mongo\node_modules\multer\index.js:8:3) at wrappedFileFilter (C:\Users\91807\Desktop\mongo\node_modules\multer\index.js:44:7) at Busboy. (C:\Users\91807\Desktop\mongo\node_modules\multer\lib\make-middleware.js:114:7) at Busboy.emit (events.js:209:13) at Busboy.emit (C:\Users\91807\Desktop\mongo\node_modules\busboy\lib\main.js:38:33) at PartStream. (C:\Users\91807\Desktop\mongo\node_modules\busboy\lib\types\multipart.js:213:13) at PartStream.emit (events.js:209:13) at HeaderParser. (C:\Users\91807\Desktop\mongo\node_modules\dicer\lib\Dicer.js:51:16) at HeaderParser.emit (events.js:209:13) at HeaderParser._finish (C:\Users\91807\Desktop\mongo\node_modules\dicer\lib\HeaderParser.js:68:8) at SBMH. (C:\Users\91807\Desktop\mongo\node_modules\dicer\lib\HeaderParser.js:40:12) at SBMH.emit (events.js:209:13) at SBMH._sbmh_feed (C:\Users\91807\Desktop\mongo\node_modules\streamsearch\lib\sbmh.js:159:14) at SBMH.push (C:\Users\91807\Desktop\mongo\node_modules\streamsearch\lib\sbmh.js:56:14)


回答1:


const mongoURI = 'mongodb+srv://caman3874:qwertyuiopaman1234@@amanco-pexfz.mongodb.net/test?retryWrites=true&w=majority';

const promise = mongoose.connect(mongoURI, { useNewUrlParser: true });

const conn = mongoose.connection;
let gfs;

conn.once('open',() => {
  gfs = Grid(conn, mongoose.mongo);
  gfs.collection('uploads');
});

//create storage object
const storage = new GridFsStorage({
  db: promise,
  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 });

Hope this works!



来源:https://stackoverflow.com/questions/58173677/error-the-database-connection-must-be-open-to-store-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!