【问题标题】:Cannot call method 'get' of undefined using mongodb with express无法使用带有express的mongodb调用未定义的方法'get'
【发布时间】:2015-10-25 10:06:38
【问题描述】:

我按照教程进行操作,但不知道出了什么问题。我的 cmd 完全没有错误。当我打开 localhost:3000 时,我看到了这个错误 Cannot call method 'get' of undefined 并且无法在我的帖子集合中加载帖子。

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

我的玉

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

【问题讨论】:

标签: javascript node.js mongodb express pug


【解决方案1】:

有问题, 您需要先将 db 附加到 req 对象,然后使用它。将此功能放在所有路线之前。

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

then use it in route.

var dbs = req.db;

否则很简单,删除此行并运行您的应用程序。

var db = req.db;

完整代码

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

【讨论】:

  • 你的完整代码是我的 index.js 吗?我的应用未定义
  • 请重新检查您的代码,我已经在我的系统上测试了我的代码,然后才将它放在这里。确保您已经安装了所有依赖项,并且还通过执行 var app = express(); 创建了 app 对象
  • 我在 app.use.res.render.message (C:\wamp\www\node_blog\app.js:81:13) 收到此错误
  • 请将您的代码放在 pastebin 并在此处放置链接
  • 奇怪的是为什么找不到,嗯
猜你喜欢
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2016-03-22
  • 2019-09-24
  • 2013-09-22
相关资源
最近更新 更多