【问题标题】:NodeJS-Mongo: Querying the database and gridfs and returning both the document and the image to the userNodeJS-Mongo:查询数据库和gridfs并将文档和图像返回给用户
【发布时间】:2014-11-29 06:07:06
【问题描述】:

我正在尝试使用 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') ; 

【问题讨论】:

    标签: node.js mongodb express gridfs


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多