无法使用 mongodb 和 express 调用未定义的方法 'get'
Cannot call method 'get' of undefined using mongodb with express
我按照教程进行操作,但不知道哪里出了问题。我的cmd完全没有错误。当我打开 localhost:3000 时,我看到了这个错误 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
});
});
});
我的玉
block content
if posts
each post, i in posts
h1=post.title
有问题,
您需要先将 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);
我按照教程进行操作,但不知道哪里出了问题。我的cmd完全没有错误。当我打开 localhost:3000 时,我看到了这个错误 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
});
});
});
我的玉
block content
if posts
each post, i in posts
h1=post.title
有问题, 您需要先将 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);