【问题标题】:Data from Mongo in Gulp using Gulp Data使用 Gulp Data 在 Gulp 中获取来自 Mongo 的数据
【发布时间】:2016-12-18 22:17:06
【问题描述】:

在使用 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))}));
     });

当我使用原型数据库时,我可以运行,

> db.heroes.findOne()

得到这个结果:

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

【问题讨论】:

    标签: javascript node.js mongodb gulp gulp-data


    【解决方案1】:

    您可以将cb(undefined, db.collection('heroes').findOne());这一行更改为喜欢下面的行,

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

    或如下简写,

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

    所以你上面简化的 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))}));
         });
    

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      相关资源
      最近更新 更多