node.js - Store file with Mongoose/GridFS with FeathersJs -
building rest api feathersjs need able upload picture (post), record if gridfs , able later.
i start set gridfs mongoose:
const mongoose = require('mongoose'); const grid = require('gridfs-stream'); grid.mongo = mongoose.mongo; module.exports = function () { const app = this; mongoose.connect(app.get('mongodb')); const cnx = mongoose.connection; mongoose.promise = global.promise; cnx.once('open', () => { const gfs = grid(cnx.db); app.set('gfs', gfs); }) app.set('mongooseclient', mongoose); };
then add in /pub
service :
pub.service.js
const multipartmiddleware = require('multer')(); [...] app.use('/pub', multipartmiddleware.single('uri'), function(req, res, next){ req.feathers.file = req.file; next(); }, createservice(options) );
pub.hook.js
create: [ hook => { const gfs = hook.app.get('gfs'); const file = hook.params.file; console.log(hook) const writestream = gfs.createreadstream({ filename: file.originalname, content_type: file.mimetype, // image/jpeg or image/png }) const dir = __dirname; fs.createreadstream(`${__dirname}/img`).pipe(writestream); } ],
and error saying :
mongoerror: file id ### not opened writing
where ### filename instead of _id
Comments
Post a Comment