Вы можете сделать что-то вроде этого -
uploadRoute. js
// Config
const config = require('../../../config/config');
// Logic
const mongoose = require("mongoose");
const fs = require('fs');
const Grid = require('gridfs-stream');
//models
const Files = require('../../../models/files.model');
module.exports = router => {
const conn = mongoose.connection;
Grid.mongo = mongoose.mongo;
let gfs;
conn.once("open", () => {
gfs = Grid(conn.db);
router.post('/bucket/upload', (req, res) => {
let {
file
} = req.files;
let writeStream = gfs.createWriteStream({
filename: `${file.name}`,
mode: 'w',
content_type: file.mimetype
});
writeStream.on('close', function (uploadedFile) {
Files.create({
doc_id: uploadedFile._id,
length: uploadedFile.length,
name: uploadedFile.filename,
type: uploadedFile.contentType
})
.then(file => res.json({
success: true,
message: "File was saved with success"
}))
.catch(err => {
console.error(`[*] Error, while uploading new files, with error: ${err}`);
res.status(500).json({
message: `[*] Error while uploading new files, with error: ${err}`
})
})
});
writeStream.write(file.data);
writeStream.end();
});
});
}
Для gridfs вам нужно предоставить модель в пн go для Для хранения данных вы можете указать пустую модель или добавить несколько пользовательских полей, которые будут частью коллекции mon go, с некоторыми дополнительными полями, которые добавляет gridfs.
models. js
const mongoose = require('mongoose');
const fileSchema = new mongoose.Schema({
doc_id: {
type: String
},
length : {
type: Number
},
name: {
type: String
},
type: {
type: String
}
});
module.exports = mongoose.model('File', fileSchema);