2

我正在尝试创建一个照片应用程序,该应用程序存储 jpeg 和 png 等图像以及标题、描述等一些细节。我遵循了 brad traversy 的 GridFS 教程,我无法将我的猫鼬模型与 gridfs 代码相关联。

用于将数据发布到 gridfs 集合中的代码

 mongoose.Promise=global.Promise;
 mongoose.connect('', {useNewUrlParser:true}, (err, database) => {
 if (err) {
  console.log('MongoDB Connection Error. Please make sure that MongoDB is 
   running.');
   process.exit(1);
   } else{
    console.log('connection succeeded')
   }

  });



  Grid.mongo = mongoose.mongo;
 var connection = mongoose.connection;
 connection.on('error', console.error.bind(console, 'connection error:'));
 connection.once('open', function () {

    gfs = Grid(connection.db);

   router.get('/', function (req, res) {
    res.render('index');
   });
  })




const storage = new GridFsStorage({
  url: '',
  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: 'FileUploads'
    };
    resolve(fileInfo);
     });
   });
 }
});

 const upload = multer({ storage }).single('file');
router.post('/', (req, res) => {
  upload(req, res, (err) => {
   if (err) {
  return res.end('error request file');
   }

   var data = new Image({
    name : req.body.name,
      image:req.body.file
    });
    data.save().then((result) => {
  //res.send(result);
  //res.redirect('/')
    console.log('saved')
    });
   console.log(req.file);
   //res.end('upload file success');
   //res.redirect('/')
   res.redirect('/')
   console.log('success');
 });
});

This is my models file
const  express = require('express');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

  const Image = new Schema({
   name: {
  type:String
   } ,
   image :{
   type:Object.Types.SchemaId;
   ref:'GFS'
  }

 });


   const GFS = new Schema({},"fs.files" )



  module.exports = mongoose.model('Image', Image )
  module.exports = mongoose.model('GFS', GFS)

 Can you tell how i retrieve the multiple collections in one route, I want o 
 make  a crud application, using Gridfs and mongoose. 
4

0 回答 0