Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data from Mongo in Gulp using Gulp Data

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

Gulp Task (simplified)

 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!"
}
like image 527
Scott Simpson Avatar asked Dec 18 '16 22:12

Scott Simpson


1 Answers

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

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.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))}));
     });
like image 155
Aruna Avatar answered Oct 24 '22 04:10

Aruna