hello, tearing my hair out trying to implement mongoose-crate-s3, Have instantiated a model from Mongoose with the crate plugin attached, but I can’t get the uploaded file to persist, debugging is showing me that req.file is getting set but the Mongoose Model is not getting the file attached. Any ideas?
/// I am trying to use mongoose-crate-s3 to save files to S3 bucket\
/// Following instructions here: https://github.com/achingbrain/mongoose-crate-s3
/// req.file is setting but my instance of the File model based on mongoose-crate-s3 is not getting file saved to it
/// Debugging below
const mongoose = require('mongoose');
const crate = require('mongoose-crate')
const S3 = require('mongoose-crate-s3')
const path = require('path')
const FileSchema = new mongoose.Schema({
owner: { type: String },
title: { type: String },
filename: { type: String, required: [true, 'required'] }
}).set('toJSON', {
virtuals: true,
versionKey: false,
transform: function (doc, ret) { delete ret._id }
})
FileSchema.plugin(crate, {
storage: new S3({
key: 'REDACTED',
secret: 'REDACTED',
bucket: 'REDACTED',
acl: 'public-read', // defaults to public-read
region: 'eu-west-1', // defaults to us-standard
// where the file is stored in the bucket - defaults to this function
path: (attachment) => `/${path.basename(attachment.path)}`
}),
fields: {
file: {}
}
})
const File = mongoose.model('File', FileSchema)
/// THEN I HAVE A ROUTE TRIGGERING THE FOLLOWING
create(req, res, next) {
if (!req.file) {
res.status(665);
return res.json({'status' : 'failed', 'message' : 'no file attached'});
}
var fileInstance = new File()
fileInstance.title = req.body.title;
fileInstance.filename = req.file.originalname;
console.log('A', req.file);
fileInstance.attach('file', req.file, (error) => {
if (error) {
fileInstance.save((error) => {
res.status(666);
console.log('B', fileInstance)
console.log('C', fileInstance.file)
res.send(fileInstance.file.url);
});
} else {
res.status(667);
return res.json({'status' : 'failed', 'message' : error});
}
});
}
//// OUTPUT /////
HTTP/1.1 666
A { fieldname: 'file',
originalname: 'test.pdf',
encoding: '7bit',
mimetype: 'application/pdf',
buffer: <Buffer 25 50 44 46 2d 31 2e 35 0a 25 bf f7 a2 fe 0a 31 30 20 30 20 6f 62 6a 0a 3c 3c 20 2f 4c 69 6e 65 61 72 69 7a 65 64 20 31 20 2f 4c 20 33 31 33 31 32 36 ... >,
size: 313126 }
B { __v: 0,
filename: 'test.pdf',
_id: 5a9511b62c63041bac655344 }
C {}