Sco*_*son 7 javascript mongodb node.js gulp gulp-data
在使用Gulp Data时,如何从Mongo数据库中获取数据Gulp作为数据源?
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))}));
});
Run Code Online (Sandbox Code Playgroud)
当我使用原型数据库时,我可以运行,
> db.heroes.findOne()
Run Code Online (Sandbox Code Playgroud)
得到这个结果:
{
"_id" : ObjectId("581f9a71a829f911264ecba4"),
"title" : "This is the best product!"
}
Run Code Online (Sandbox Code Playgroud)
您可以将线条更改cb(undefined, db.collection('heroes').findOne());为如下所示,
db.collection('heroes').findOne(function(err, item) {
cb(undefined, item);
});
Run Code Online (Sandbox Code Playgroud)
或者如下所示,
db.collection('heroes').findOne(cb);
Run Code Online (Sandbox Code Playgroud)
所以你简化的上面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);
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))}));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313 次 |
| 最近记录: |