[英]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.