Cannot get posts from MongoDB using gulp-data

59 views Asked by At

Approach: Use gulp to create static html with posts from mongodb

Stack:: express, mongodb, pug, gulp

TL:DR I have a express app with connected mongodb and a few posts which are displayed on my landingpage. Per server everything works, it also runs on a prod-environment. But in addition to this I also want a static version of my landingpage. I know there are many fancy static site generators out there, but I'm a fan of gulp and want it handmade =)

I have this gulptask which already connects per MongoClient to my local DB (db: passport, collection: posts) and console.logs my posts

I think this is not the way, but I can log the posts in the data function successfully

gulp.task('db-test', function() {
    return gulp.src('views/index.pug')
      .pipe(data(function(file, cb) {
        MongoClient.connect('mongodb://localhost:27017/passport', function(err, db) {
          db.collection('posts').find().forEach(function(doc) {
            console.log(doc) // This logs each of my posts from the mongodb - yayy but how to pass it correctly to the pug function below?
          });
          if(err) return cb(err);
          cb(undefined, db.collection('posts').find());
      });
    }))

    .pipe(pug({
    // here Im using a static array, otherwise the posts are not logged in the data function
      locals: {posts: [{title: "blabal"}, {title: "heyhey"}]}
    }))
    // If im doing like in the instruction of gulp-data, it breaks in my template 
    // .pipe(pug({}))
    .pipe(gulp.dest('./dist'))
});

Template

ul
  each val in posts
    li= val.title

When i remove this dynamic part, the gulp taks generates my html without any problems.

The version how it should work (but doesn't)

gulp.task('db-test', function() {
 return gulp.src('views/index.pug')
  .pipe(data(function(file, cb) {
     MongoClient.connect('mongodb://localhost:27017/passport', function(err, db) {
        if(err) return cb(err);
        cb(undefined, db.collection('posts').find());
      });
    }))
   .pipe(pug({})) // now my gulp-pug tasks says cannot find length of undefined = no posts found or just accessing the Cursor from the mongo collection - i dont know...
   .pipe(gulp.dest('./dist'))
});

When i debug my gulp task i see that db.collection('posts').find() is a pending promise. I also tried to resolv that, without success.

Gulp Heros out there - help me!

0

There are 0 answers