如何将猫鼬模型与Gridfs集成以及如何关联其他字段(如req.body.name)和诸如description之类的内容

时间:2018-12-12 18:43:25

标签: node.js mongoose gridfs gridfs-stream multer-gridfs-storage

我正在尝试创建一个照片应用程序,该应用程序存储诸如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. 

0 个答案:

没有答案