0

I follow a tutorial and have no clue what's wrong. There's no error in my cmd at all. When I open localhost:3000 I saw this error Cannot call method 'get' of undefined and couldn't load the post in my posts collection.

var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');

/* Homepage blog posts */
router.get('/', function(req, res, next) {
  var db = req.db;
  var posts = db.get('posts');
  console.log(posts)
  posts.find({},{},function(err,posts){
    res.render('index',{
        "posts":posts
    });
  });
});

My jade

block content
    if posts
        each post, i in posts
            h1=post.title
1

1 Answer 1

1

There is problem, You need to first attach db to req object then use it. Place this function before all routes.

app.use(function(req, res, next) {
  // open connection
  req.db = db;
  next();
});

then use it in route.

var dbs = req.db;

Otherwise simple is, remove this line and run your app.

var db = req.db;

complete code

var express = require('express');
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');

var app = express();

app.use(function(req, res, next) {
  req.db = db;
  next();
});

app.get('/', function(req, res, next) {
  var dbPost = req.db;
  var posts = dbPost.get('posts');
  console.log(posts)
  posts.find({},{},function(err, posts){
    res.render('index',{
        posts: posts
    });
  });
});

app.listen(3000);
Sign up to request clarification or add additional context in comments.

12 Comments

your complete code is my index.js? I got app is not defined
kindly recheck your code, i have tested my code on my system before placing it here. make sure, you have installed all dependencies and also created app object by doing var app = express();
I got this error at app.use.res.render.message (C:\wamp\www\node_blog\app.js:81:13)
kindly put your code on pastebin and place link here
weird why not found, hmm
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.