How to upload Image to MongoDB and string data, simultaneously, using GridFS?

Am trying to create an app to upload and caption images, directly to mongodb using GridFs. And then create an API to show these images and caption at client side. Major Problem. This is my multer with grdifs storage engine. Works like a charm.

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

const storage = new GridFsStorage({
    url : mongoURI,
    file : (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buff) => {
                if(err){
                    return reject(err);
                }
                const filename = buff.toString('hex') +                                 path.extname(file.originalname);
                    const fileInfo = {
                        filename: filename,
                        caption :  req.body.name,
                        bucketName : 'uploads'
                    };
                    resolve(fileInfo);
                });
        });
    }
});

const upload = multer({ storage });

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

The problem is, when I try to incorporate another action using a Post Model I created, using mongoose scheme, on this route, after uploading the image,like so.

app.post('/upload', upload.single('file'), (req, res) =>{
    const newPost = new Post({
        caption : req.body.caption,
        image :  req.file.filename
    })
    newPost.save()
        .then(post => res.json('Posted'))
        .catch(err => console.log(err)) ;
    //res.json({file : req.file});

}); The server just gets stuck on loading. So, my question is, does using gridfs, change how we normally use mongoose models with MongoDB?

My Post model (post.js)

const mongoose = require('mongoose');
const Schema = mongoose.Schema; 

//Post Schema
let PostSchema = new Schema({
  caption : {
    type : String,
    required : true
  },
  image : {
    type: String,
    required: true
  }
});     

let Post = module.exports = mongoose.model('Post', PostSchema);

I want to use this Post collection, to store the image’s filename that was uploaded, along with caption from client. Am doing something wrong, and I need help.

Another problem, right now am using a form to make this POST request. But when I try to use axios to make a post request to my API port(i.e 5000) from my client port(i.e 8080), I get CORS error. How do I overcome this? Any help is much appreciated. Thank you! :slight_smile:

You need to proxy 5000 via 8080