lykmapipo / mongoose-gridfs

mongoose gridfs on top of new gridfs api
MIT License
91 stars 39 forks source link

collection parameter ignored #25

Closed mkilp closed 6 years ago

mkilp commented 6 years ago

So what I want to do are 2 Gridfs Collections: Categories & Profile Pictures

I Insert my files with the following function into the categories bucket:

function insertFile(file, callback) {
    let gridfs = require('mongoose-gridfs')({
        collection: 'categories',
        model: 'Attachment',
        mongooseConnection: db
    });
    //DEBUG
    let Attachment = gridfs.model;

    let filePath = path.join(pathString, file);
    Attachment.write({
            filename: file,
            contentType: 'image/png'
        },
        fs.createReadStream(filePath), function (error, createdFile) {
            if(error)
            {
                callback(error, null);
            }
            else
            {
                callback(null, createdFile);
            }
        });
}

For the profile pictures I use the exact same syntax but with the collection changed:

function insertFile(file, callback) {
    let gridfs = require('mongoose-gridfs')({
        collection: 'profilePictures',
        model: 'Attachment',
        mongooseConnection: db
    });
    let Attachment = gridfs.model;
    const readable = toStream(file.buffer);
    Attachment.write({
            filename: file.originalname,
            contentType: file.mimetype
        },
        readable, function (err, createdFile){
            if(err)
            {
                callback(err, null);
            }
            else
            {
                callback(null, createdFile);
            }
        });
}

However the gridfs system is not recognizing the change and still putting the pictures in the categories bucket.

Is this a possible bug?

lykmapipo commented 6 years ago

@Nop0x as per L86 if you pass same model option it will reuse previouse registered mongoose model.

To fix it please use different model name as

  1. For categories

    require('mongoose-gridfs')({
        collection: 'categories',
        model: 'CategoryAttachment',
        mongooseConnection: db
    });
  2. For profile pictures

    require('mongoose-gridfs')({
        collection: 'profilePictures',
        model: 'ProfileAttachment',
        mongooseConnection: db
    });