【发布时间】: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