2

I am trying to create a photo application that stores images like jpeg and png along with some details like title, description. I following brad traversy's GridFS tutorial I am unable to associate my mongoose model with gridfs code.

The code that works for posting the data into the gridfs collection

 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. 
ALOK
  • 31
  • 1
  • 7
  • Why do you need to include data inside GridFs? Wouldn't be better to add an `id` to your schemas that points to the file instead of trying to do that in reverse. Plain data in MongoDb is always easier to access because files will be bigger and therefore data access will be slower. Just save the resulting `id` from the file in the schema and read the file only when you actually need it. – devconcept Dec 24 '18 at 17:05
  • Thanks a lot for the reply, I did exactly as you told me, I created a two models one containing the User's schema and the other holding the "fs.files " collection(as Gridfs collection), the problem is i am able to post the data to mlab, but i am unable to retrieve the data back from the gridfs collection and user collection, could you suggest a way out for this i am stuck for days without much help – ALOK Dec 26 '18 at 03:51
  • Do not try to access the `fs` collection directly. Use [`GridFsBucket`](http://mongodb.github.io/node-mongodb-native/3.0/api/GridFSBucket.html) for that. Those are files so you must use streams to save and read data. – devconcept Dec 26 '18 at 14:04
  • Thank You Sir for your patience and appreciate your efforts to help a novice like me, Your replies were very helpful – ALOK Dec 26 '18 at 16:58
  • Hey, I am using gridfs but I have some problems with how should I use it. Do you have any real project link for me to take as an example? – Ensar Eray Feb 24 '21 at 07:46

0 Answers0