0

I want to upload images using mongoose-gridfs. And I am having the following Problem (The one I show below in the photo). It is with the use of mongoose-gridfs and I would like if someone has worked with this library and in the way that I structure it below, it will help me to solve my situation or update me if there is a newer way to do it following this same structure. Thanks in advance.

This image show the error when i try to execute my code

Here my model Attachment

'use strict'

const mongoose = require('mongoose');

const gridfs = require('mongoose-gridfs')({ // TypeError: require(...) is not a function
    collection: 'attachments',
    model: 'Attachment'
});
const AttachmentSchema = gridfs.schema;


module.export = mongoose.model('Attachment', AttachmentSchema);

Here my model User where I pass Attachment as ref to the photo atributte

'use strict'

require('mongoose-type-email');

const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');
const uniqueValidator = require('mongoose-unique-validator');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
     first_name: {type: String, required: true},
     email: {type: mongoose.SchemaTypes.Email, required: true, unique: true},   
     password: {type: String, required: true},   
     active: {type: Boolean, default: false},
     created: {type: Date, default: Date.now()},
     photo: {type: Schema.ObjectId, ref: "Attachment"},
     valid_token: {type: String},

});

Now my fileService.js service that I use to upload the images.

'use strict'

const Attachment = require('../models/Attachment');
const im = require('imagemagick');
const fs = require('fs');
const   events = require('events');

const gridfs = require('mongoose-gridfs')({ //TypeError: require(...) is not a function
    collection: 'attachments',
    model: 'Attachment'
});

exports.uploadFile = function (file, cb) {
    const eventEmitter = new events.EventEmitter();
    const lista = Object.values(file);
    const properties = Object.getOwnPropertyNames(file);
    const result = [];
    const listLength = lista.length;

   eventEmitter.once('err', err => {
        cb(err);
   });

   eventEmitter.once('upload', lista => {
      cb(null, lista);
   });

   eventEmitter.on('uploadFinish', (obj, property) => {

       obj.contentType.startsWith("image") ? result.push({
           type: 'img',
           'property': property,
           'value': obj
       }) : result.push({type: 'video', 'property': property, 'value': obj})

       if (listLength == result.length)
           eventEmitter.emit("upload", result);
   });

    lista.length != 0 ? fileWrite(lista, properties, eventEmitter) : eventEmitter.emit("upload");
};

function fileWrite(lista, properties, eventEmitter) {

   const files = Array();
   const Attachment = gridfs.model;

   lista.forEach((element, index) => {
       Attachment.write({
           filename: element.name,
           contentType: element.type
       },
       fs.createReadStream(element.path),
       (err, createdFile) => {
           err ? eventEmitter.emit('err', err) : eventEmitter.emit('uploadFinish', createdFile, 
           properties[index]);
      });
   });
}

Here is my userService.js where I call the uploadFile function of the fileService.js service

'use strict'

const User = require('../models/User');
const fileService = require('../services/fileService');

exports.save = function (file, data, res) {
   fileService.uploadFile(file, (err, files) => {
      if (!err) {
        if (files) {
            files.forEach((e) => {
                if (e.property == "photo") {
                    data.photo = e.value;
                }
            });
        }

        data['created'] = new Date();
        const user = new User(data);
        user.save((err, user) => {
            if (!err) {
                user.update(data, (error) => {
                    if (!error) {
                        res.json({success: true, message: "Inserted user", data: user})
                    } else {
                        res.send({
                            success: false,
                            message: 'User cant be updated'
                        });
                    }
                });
            } else
                res.status(500).send({success: false, message: 'Error trying to save the user'});
        });
     } else {
        res.status(500).send({success: false, message: 'Error trying to upload files'});
     }
  });
};
Mario
  • 1
  • I want to suggest you that do not store images in mongo use file system instead for more speed and full utilization – mehta-rohan Apr 16 '20 at 14:22

1 Answers1

0

mongoose-gridfs specifies a different way of using it here:

const { createModel } = require('mongoose-gridfs');

etc.

See here for your specific error.

D. SM
  • 13,584
  • 3
  • 12
  • 21