NodeJS-Mongo:查询数据库和gridfs,并将文档和图像返回给用户

时间:2014-10-04 09:41:41

标签: node.js mongodb express gridfs

我正在尝试使用nodejs,express和mongodb构建一个应用程序。我正在使用GRIDfs存储图像。我可以检索文档和图像单独

如何查询mongo数据库和gridfs,并将文档和图像作为对用户的响应返回?

这是我的代码 - >

wines.js

var mongo = require('mongodb') ;

var Server = mongo.Server,
    Db=mongo.Db,
    BSON=mongo.BSONPure,
    fs = require('fs'),
    Binary=mongo.Binary,
    GridStore=mongo.GridStore,
    Code=mongo.Code,
    ObjectID=mongo.ObjectID,
    assert=require('assert'); 

 var buffer = "";

var Grid = require('gridfs-stream');
var server = new Server('localhost',27017,{auto_reconnect:true});

db = new Db('winedb',server) ; 

db.open(function(err,db){
    if(!err){
        console.log("Connected to 'wine.db' database") ; 
        db.collection('wines',{strict:true},function(err,collection){
               if(err){
                    console.log("The 'wines' collection doesn't exist creating it") ;
                    populateDB() ;  
               }

        });




}

});





exports.findById = function(req,res){
    var id = req.params.id ;
    console.log('Retrieving wine:'+id) ; 
    db.collection('wines',function(err,collection){
            collection.find({'_id':new BSON.ObjectID(id)}).toArray(function(err,items){ 

           res.writeHead(200,{'Content-Type':'application/json'});    
           res.writeContinue(items) ;
           res.addTrailers({'Content-Type':'image/jpeg'}); 

           var gfs = Grid(db,mongo);


    try {


        var readstream = gfs.createReadStream({'_id':ObjectID(items[0].image_id)});

        readstream.pipe(res);
        console.log("sending image") ; 



} catch (err) {
    console.log(err);
    console.log("File not found.");
} 
        });



});


}    


var populateDB = function(){

    var wines = [
        {
        name: "CHATEAU DE SAINT COSME",
        year: "2009",
        grapes: "Grenache / Syrah",
        country: "France",
        region: "Southern Rhone",
        description: "The aromas of fruit and spice...",
        picture: "saint_cosme.jpg"
    },
    {
        name: "LAN RIOJA CRIANZA",
        year: "2006",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "A resurgence of interest in boutique vineyards...",
        picture: "lan_rioja.jpg"
    }];


    db.collection('wines',function(err,collection){
            collection.insert(wines,{safe:true },function(err,result){});
    });

       var gfs = Grid(db,mongo);
       var fileId = new ObjectID();

         var writestream = gfs.createWriteStream({
            filename:'white',
            mode:'w',
            contentType:'image/png',
            _id:fileId,
         });

         fs.createReadStream('./images/white.jpg').pipe(writestream);

            db.collection('wines',function(err,collection){
                 collection.update({year:'2009'},{$set:{image_id:fileId}},{safe:true},function(err,result){

                if(err){
                    console.log('Error updating wine:'+err) ;
                }
                else{
                    console.log(''+result+'document(s) updated') ; 

                }
            }
    )}
);






};

server.js

var express = require('express')  , 
wines = require('./routes/wines'); 

var Grid = require('gridfs-stream')  ; 
var app = express(); 

app.configure(function(){
    app.use(express.logger('dev'));
    app.use(express.bodyParser()); 
}) ; 
app.get('/wines',wines.findAll); 

app.get('/wines/:id',wines.findById);

app.post('/wines',wines.addWine) ; 

app.put('/wines/:id',wines.updateWine); 

app.delete('/wines/:id',wines.deleteWine) ; 

app.get('/image/:id',wines.display); 

app.listen(3000) ; 
console.log('Listening on port 3000') ; 

1 个答案:

答案 0 :(得分:0)

或者,您可以将图像存储在S3中。获取网址。将该URL存储到您的BSON文档中。当您发送响应时,客户端将请求图像URL并显示该URL。

如果您只考虑发送图像进行显示,则这是当然的。如果您需要处理图像并需要在系统之间发送图像,则可以将图像转换为base64字符串并将其作为字段添加到BSON文档中。但是,如果图像大小很大,可能会导致多个请求的流量。

您也可以使用Kraken.IO来优化图像。