来自Gulp的Mongo使用Gulp数据的数据

时间:2023-01-24 11:33:15

How can I get data from my Mongo database to pipe in Gulp as a data source when using Gulp Data?

在使用Gulp Data时,如何从我的Mongo数据库中获取数据作为数据源在Gulp中管道?

Gulp Task (simplified)

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))}));
     });

When I am using the prototype database, I can run,

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

> db.heroes.findOne()

And get this result:

得到这个结果:

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

1 个解决方案

#1


5  

You can change the line cb(undefined, db.collection('heroes').findOne()); to like the one as below,

你可以改变行cb(undefined,db.collection('heroes')。findOne());喜欢下面这个,

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

OR as below as a short hand,

或者如下所示,

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

So your simplified above Gulp task becomes,

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

#1


5  

You can change the line cb(undefined, db.collection('heroes').findOne()); to like the one as below,

你可以改变行cb(undefined,db.collection('heroes')。findOne());喜欢下面这个,

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

OR as below as a short hand,

或者如下所示,

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

So your simplified above Gulp task becomes,

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