我目前正尝试通过特定视图在mongodb中显示集合的内容。我想把它放在哪里,如果没有上述收藏的内容,它只会跳过但被告知mongodb不需要。但是,当我尝试运行以下jade模板时,我收到上面列出的错误消息。
应该从集合中获取数据的路径中的js文件,是否为空。
router.get('/commentList', function(req, res) {
var db = req.db;
var comments = db.get('comments');
comments.find({},{},function(e,docs){
res.render('commentList', {
"commentList" : docs
});
});
});
和正在播放的jade文件中的视图代码
h2
Comments
ul
each comment, i in commentList
li
p comment.commentContent - comment.created_on - comment.author
我可以看到可能导致错误的onyl事件是一个空集合但是你会怎么说"如果集合是空的,请执行以下操作?"为了避免上述错误,假设问题是什么?
编辑:我在数据库中配备了内容,但仍然收到相同的错误消息,所以至少不是因为数据库集合是空的。编辑#2:如果评论是mongo驱动程序集合或mongoose,则会有问题。我不完全确定(我认为它是Mongoose,因为它创建了连接),但这是它在app.js中的声明方式
var mongo = require('mongodb');
var Mongoose = require('mongoose');
var db = Mongoose.createConnection('localhost', 'acl');
编辑#3:尝试更改连接,因此它直接使用mongo连接,而不是通过mongoose。这是代码
var mongo = require('mongodb'),Server = mongo.Server,Db = mongo.Db;
var server = new Server('localhost', 27017, {safe:true});
var db = new Db('acl', server);
错误仍然相同。
编辑#4:我已经废弃了这个副本并重新开始,因为我怀疑多个教程的混合已经使这个狗破解了代码,并且可以更快地点击重置按钮答案 0 :(得分:1)
试试这个:
router.get('/commentList', function(req, res) {
req.db.get('comments').find({},{},function(e,docs){
res.render('commentList', {
commentList : docs || []
});
});
});
答案 1 :(得分:1)
鉴于您的代码,请尝试:
var mongoose = require('mongoose');
mongoose.model('comment', new Schema( {/*your data schema*/} );
router.get('/commentList', function(req, res) {
var db = req.db;
var comment = db.model('comment');
comment.find({}, function(e,docs){
res.render('commentList', {
"commentList" : docs
});
});
});
参考:http://mongoosejs.com/docs/api.html#index_Mongoose-model
<强>更新强>:
我添加了一个明确的模型定义。确保您的集合被称为comments
。要测试这个,你可以打开一个mongodb shell并运行:use ac1; db.comments.find({})
(我假设你的数据库名称是ac1),并确保你获得了任何数据。
此外,您尝试将连接命令更改为:mongoose.connect('mongodb://localhost/ac1');
更新2 :
您可以通过添加回调来检查渲染是否引发错误:
res.render('commentList', {"commentList" : docs}, function( err, html ) {
//Inspect err.
});
答案 2 :(得分:1)
我通过将mongoose更新到最新版本来修复它。 我希望它会有所帮助!