gpt4 book ai didi

node.js - NodeJS-Mongo : Querying the database and gridfs and returning both the document and the image to the user

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:38 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于node.js - NodeJS-Mongo : Querying the database and gridfs and returning both the document and the image to the user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com