简体   繁体   English

无法使用带有Express的mongodb调用未定义的方法“ get”

[英]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. 我的cmd完全没有错误。 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. 当我打开localhost:3000时,看到此错误无法调用未定义的方法“ get”,并且无法将帖子加载到我的帖子集合中。

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. 有问题,您需要先将db附加到req对象,然后再使用它。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在express js中调用未定义的方法“发送”(响应未定义) - Cannot call method 'send' of undefined(response is undefined) in express js Coffeescript + Express.js:无法调用未定义的“切片”方法 - Coffeescript + Express.js : cannot call method 'sliced' of undefined TypeError:无法调用未定义的方法“ get” - TypeError: Cannot call method 'get' of undefined MongoDB aggregate() - 错误“TypeError:无法调用方法'forEach'未定义” - MongoDB aggregate() - error “TypeError: Cannot call method 'forEach' of undefined” MongoDB Javascript replace() 失败并显示“TypeError:无法调用未定义的方法‘replace’” - MongoDB Javascript replace() fails with "TypeError: Cannot call method 'replace' of undefined" 无法调用未定义的on方法 - Cannot call method of on of undefined 无法调用未定义的方法… - Cannot call method … of undefined '未定义' object 使用 MongoDB + Express - 'undefined' object using MongoDB + Express 使用then()调用其他两个函数:错误-无法调用未定义的方法“ then” - Using then() to call two other functions : Error - Cannot call method “then” of undefined TypeError:无法在socket.handshake调用未定义的方法“ get” - TypeError: Cannot call method 'get' of undefined at socket.handshake
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM