Friday, 11 May 2018

Save S3 link to MongoDb when uploading files

I have this code that uploads files to my S3 bucket. I would like to save the link to MongoDb schema in the userPicture field.My userschema has the following fields.const UserSchema = new Schema( { email: {type: String}, userPicture: {type: String} } ); Create is the function that created a new user.function create(req, res, next) { const body = req.body; try { await User.create(body); return res.status(HTTPStatus.CREATED).json({message: 'Account created.'}); } catch (e) { e.status = HTTPStatus.BAD_REQUEST; return next(e); } } Upload functionconst S3 = new AWS.S3(); export function S3Upload(req, res) { const chunks = []; let fileType; let fileEncodingType; const busboy = new Busboy({ headers: req.headers }); busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { filename.replace(/ /g, "_"); fileType = mimetype; fileEncodingType = encoding; file.on('data', data => { chunks.push(data) }); file.on('end', () => { console.log(`File [${filename}] Finished`); }); }); busboy.on('finish', () => { const userId = UUID(); const params = { Bucket: BUCKET_NAME, Key: userId, Body: Buffer.concat(chunks), ACL: ACL, ContentEncoding: fileEncodingType, ContentType: fileType } S3.upload(params, (err, s3res) => { if (err) { res.send({ err, status: 'error' }); } else { res.send({ data: s3res, status: 'success', msg: 'Image successfully uploaded.' }); } }); }); req.pipe(busboy); } The upload to S3 works perfectly and I get a link to the file uploaded. I know I have to do something before the res.send() function in upload. But I don't know how and what to do. Any help would be appreciated

Submitted May 11, 2018 at 08:06AM by LastApplication

No comments:

Post a Comment