Reputation: 1381
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
Upvotes: 0
Views: 519
Reputation: 742
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);
Upvotes: 1