在Node.js中读/写二进制数据到MongoDB

时间:2014-07-09 06:59:09

标签: node.js mongodb bson

我已经能够成功地将Node.js中的二进制数据(图像)写入MongoDB。但是我找不到关于如何阅读它的明确文档。

以下是我将图像写入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 ...”这样的函数。谢谢!

1 个答案:

答案 0 :(得分:3)

找到答案:

        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));
        }
    });