MongoDB 保存二进制文件


MongoDB 保存二进制文件

  • 定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict';

var async = require('async');
var mongodb = require('./mongodb');

var Schema = mongodb.mongoose.Schema;

var playersSchema = new Schema({
id: { type: String, unique: true },
binData: { type: Buffer}, // 存档二进制文件数据
}, { versionKey: false });

// 创建模块
module.exports = mongodb.mongo_connection.model('players', playersSchema, 'players');
  • 保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
exports.upload = async function(req, res) {
log.info(' upload begin');
try{
if(!req.body.id) return res.status(200).send({});
var id = req.body.id;
var player = await players.findOne({id: id});
if(!player) return res.status(200).send({});
// 读取文件
var fileName = req.files[0].path;
var data=fs.readFileSync(fileName);
player.binData = data;
await player.save();
return res.status(200).send({});
}catch (exp){
log.error(' upload error:' + exp);
return res.status(200).send({});
}
};