在Node.js中将二进制数据读/写到MongoDB [英] Read/write binary data to MongoDB in Node.js

查看:108
本文介绍了在Node.js中将二进制数据读/写到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够在Node.js中成功地将二进制数据(图像)写入MongoDB.但是,我找不到清晰的文档来阅读它.

I've been able to successfully write binary data (an image) to MongoDB in Node.js. However I can't find clear documentation on how to read it back.

这是我将图像写入MongoDB的方式:

Here's how I'm writing the image to MongoDB:

var imageFile = req.files.myFile;
var imageData = fs.readFileSync(imageFile.path);

var imageBson = {};
imageBson.image = new db.bson_serializer.Binary(imageData);
imageBson.imageType = imageFile.type;

db.collection('images').insert(imageBson, {safe: true},function(err, data) {

对于使用Node从Mongo读取图像的任何指示,我将不胜感激.我假设有一个类似"db.bson_deserializer ..."的函数.谢谢!

I'd appreciate any pointers on reading the image from Mongo using Node. I'm assuming there's a function like "db.bson_deserializer...". Thanks!

推荐答案

找到了答案:

        var imageFile = req.files.myFile;
    fs.exists(imageFile.path, function(exists)  {

        if(exists)
        {
            console.log("File uploaded: " + util.inspect(imageFile));
            fs.readFile(imageFile.path, function(err, imageData) {
                if (err) {
                    res.end("Error reading your file on the server!");
                }else{
                    //when saving an object with an image's byte array
                    var imageBson = {};
                    //var imageData = fs.readFileSync(imageFile.path);
                    imageBson.image = new req.mongo.Binary(imageData);
                    imageBson.imageType = imageFile.mimetype;
console.log("imageBson: " + util.inspect(imageBson));

                    req.imagesCollection.insert(imageBson, {safe: true},function(err, bsonData) {

                        if (err) {
                            res.end({ msg:'Error saving your file to the database!' });
                        }else{
                            fs.unlink(imageFile.path); // Deletes the file from the local disk
                            var imageBson = bsonData[0];
                            var imageId = imageBson._id;
                            res.redirect('images/' + imageId);
                        }
                    });
                }
            });
        } else {
            res.end("Oddly your file was uploaded but doesn't seem to exist!\n" + util.inspect(imageFile));
        }
    });

这篇关于在Node.js中将二进制数据读/写到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆