我使用Mongoose将小型base64编码图像(每个大约100-200K)直接发布到mongodb中。在存储之前,我可以看到内容与从客户端发送的内容相同。但查询base64字符串与进入的内容不同?知道我错过了什么吗?
// process the add image request
app.post('/addimage', function(req, res) {
console.log("Addimage post....");
var qry = {'_email' : req.user.local.email, 'date' : req.body.date, 'subject' : req.body.subject };
Item.findOne(qry, function(err, item) {
if (err) {
console.log('Find images failed: ' + err);
var resp = '{"result" : "failed", "msg" : ' + err + ', "_req" : "addimage"}';
res.send(resp);
} else {
if (item == null) { // item doesn't exist, create now
var item = new Item();
item._email = req.body._email;
item.date = req.body.date;
item.subject = req.body.subject;
}
// add image
var image = new Image();
image.timestamp = req.body.timestamp;
image.contentType = req.body.contentType;
var imgBuf = new Buffer(req.body.image, 'base64');
image.image = imgBuf;
item.images.push(image);
item.save(function(err, result) {
if (err) {
console.log('Find images failed: ' + err);
var resp = '{"result" : "failed", "msg" : ' + err + ', "_req" : "addimage"}';
res.send(resp);
} else {
res.send('{"result" : "ok", _req: "addimage"}');
console.log("Image saved and responded to ...");
}
});
}
});
});
存储在req.body.image中的数据字符串以“/ 9j / 4AAQSkZJ ...”开头,但是从mongo shell我发现它有所不同。 Bindata的子类型是否导致了这个?
> db.items.find({subject:"Science"},{'images.image':1})
{ “_id”:的ObjectId( “547382943fc884447a767d58”), “图像”:[{ “图像”:BinData(0,“LwA5AGoALwA0AEEAQQBRAFMAawBaAEoAUgBnAEEAQgBBAFEAQQBBAEEAUQBBAEIAQQBBAEQALwA0AFEAQgBZAFIAWABoAHAAWgBnAEEAQQBUAFUAMABBAEsAZwBBAEEAQQBBAGcAQQBBAGcARQBTAEEAQQBN
架构:
var imageSchema = new mongoose.Schema({
timestamp : String,
contentType : String,
image : Buffer,
}, { strict: true });
imageSchema.index({ timestamp: 1}, { unique: true });
var itemSchema = new mongoose.Schema({
_email : {
type: String,
required: true,
},
date : {
type: String,
required: true,
},
subject : {
type: String,
required: true,
},
images : [imageSchema],
}, { strict: false });
itemSchema.index({ _email: 1, date: 1, subject: 1}, { unique: true });
Mongodb版本2.6.5,Mongoose 3.8.1,节点v0.11.6-pre
此外,在创建Buffer对象时尝试'utf8'/'ascii'/'ucs2'而不是'base64'。
谢谢!
答案 0 :(得分:0)
这是节点版本;(恢复到0.10.33解决了这个问题!