简体   繁体   中英

Cannot call method 'get' of undefined using mongodb with express

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM