2016-12-18 46 views
7

如何在使用Gulp數據時從我的Mongo數據庫獲取數據作爲數據源的管道Gulp使用Gulp數據來自Mongo的Gulp

咕嘟咕嘟任務簡化

gulp.task('db-test', function() { 
    return gulp.src('./examples/test3.html') 
     .pipe(data(function(file, cb) { 
      MongoClient.connect('mongodb://127.0.0.1:27017/prototype', function(err, db) { 
       if(err) return cb(err); 
       cb(undefined, db.collection('heroes').findOne()); // <--This doesn't work. 
      }); 
     })) 
     //.pipe(data({"title":"this works"})) -> This does work 
     .pipe(through.obj(function(file,enc,cb){console.log('file.data:'+JSON.stringify(file.data,null,2))})); 
    }); 

當我使用的原型數據庫,我可以運行,

> db.heroes.findOne() 

而得到這樣的結果:

{ 
    "_id" : ObjectId("581f9a71a829f911264ecba4"), 
    "title" : "This is the best product!" 
} 

回答

5

您可以更改該行cb(undefined, db.collection('heroes').findOne());喜歡上了一個如下,

db.collection('heroes').findOne(function(err, item) { 
    cb(undefined, item); 
}); 

或者按照下面的手短,

db.collection('heroes').findOne(cb); 

所以你上面咕嘟咕嘟的任務變得簡單,

gulp.task('db-test', function() { 
    return gulp.src('./examples/test3.html') 
     .pipe(data(function(file, cb) { 
      MongoClient.connect('mongodb://127.0.0.1:27017/prototype', function(err, db) { 
       if(err) return cb(err); 
       db.collection('heroes').findOne(cb); 
      }); 
     })) 
     //.pipe(data({"title":"this works"})) -> This does work 
     .pipe(through.obj(function(file,enc,cb){console.log('file.data:'+JSON.stringify(file.data,null,2))})); 
    });