我设法将文件上传到我的mongoDB数据库中,如下所示:
uploadFile(file, uid) {
var grid = require('gridfs-stream');
var mongoose = require('mongoose');
var fs = require('fs');
mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
var conn = mongoose.connection;
grid.mongo = mongoose.mongo;
const gfs = grid(conn.db);
const writeStream = gfs.createWriteStream({
filename: file.filename,
});
fs.createReadStream(file.path).pipe(writeStream);
writeStream.on('close', file => {
const {_id} = file;
console.log(`${_id} written to the db`);
return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(r => console.log(r)).catch(e => console.log(e));
});
}
所以这导致了:
{
"_id": {
"$oid": "5bc9d28270e5375dfbfe17fd"
},
"employer": {
"logo": "5bd72702d5dfad7f0f9f8c08",
},
}
它还创建了fs.files
和fs.chunks
个文档
{
"_id": {
"$oid": "5bd72702d5dfad7f0f9f8c08"
},
"filename": "6d6104894af7d98779430a7457ce3e4e",
"contentType": "binary/octet-stream",
"length": 17283,
"chunkSize": 261120,
"uploadDate": {
"$date": "2018-10-29T14:09:18.725Z"
},
"aliases": null,
"metadata": null,
"md5": "2e6afedd69510b1b526f1015c47065e2"
}
这在fs.chunks
{
"_id": {
"$oid": "5bd72702d5dfad7f0f9f8c09"
},
"files_id": {
"$oid": "5bd72702d5dfad7f0f9f8c08"
},
"n": 0,
"data": "<Binary Data>"
}
所以我觉得这很好。但是现在我不知道该怎么读。这就是我到目前为止所拥有的。
downloadFile: async id => {
var fs = require('fs');
fs.file.find(id).then(r => console.log(r)).catch(e => console.log(e));
}
我在互联网上看到了类似的内容,但现在找不到。知道这怎么了吗?