2014-06-21 52 views
0

我正在寻找我的问题,但即使不知道问题出在哪里。Nodejs,Mongoose和Jade没有从数据库中获得数据

我得到它在我的路线设置标题,但没有从数据库中的数据...

我的模型:

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    ObjectId = Schema.Types.ObjectId; 


var blogSchema = new Schema({ 
    title: { type: String, required: true }, 
    author: { type: String, required: true }, 
    body: { type: String, required: true }, 
    date: { type: String, required: true }, 
    hidden: Boolean 
}); 


module.exports = mongoose.model('Blog', blogSchema); 

我的路由器:

var express = require('express'), 
    Blog = require('../models/blog'), 
    moment = require('moment'); 

moment.lang('de'); 

var router = express.Router(); 


router.get('/articles', function(req, res) { 
    Blog.find(function(err, docs){ 
     return res.render('blog/articles', { 
      title: 'Blog_', 
      articles: docs 
     }); 
    }); 
}); 

app.use('/blog', router); 

我玉

extends ../layouts/default 
include ../elements/form-elements 

block content 

    h1= title 
    each article in articles 
     .col-md-12 
      div.title= article.title 

the只有一个我在页面显示是

Blog_ 

所以我做错了什么?

在错误的文件,只说:“不能读取属性‘标题’的未定义”

所以文章对象未设置......但是为什么呢?

非常感谢

编辑1:

变化article.title第不会改变任何东西在日志文件中

GET /blog/articles HTTP/1.1 304 - - 3 ms 

编辑2 :

似乎节点犯规从数据库获取任何数据... 和是有一个TESTDATA集;)

的console.log() - >

错误:空

文档: []

的解决办法是张贴答案

+0

模型部分,你可以改变'article.title'到'article'玉石用于测试目的?我怀疑'article'是未定义的,因此解释了你的错误信息。 – alandarev

+0

尝试''console.log(docs)'在那里。我知道没有标准,但是你已经在我希望的地方发布了'.connect'。 –

回答

0

得到了解决......

模型是不正确的......

var blogSchema = new Schema({ 
    title: { type: String, required: true }, 
    author: { type: String, required: true }, 
    body: { type: String, required: true }, 
    date: { type: String, required: true }, 
    hidden: Boolean 
}, {collection : 'blog'}); 

有名字在最后集合......导致其写在小字母-.-

什么错误的 - 从来没有做到这一点再次^^

0

我知道这是一个非常古老的问题,它的OP作为回答标记,但我认为真正的问题是在“我的路由器”,你没有引用你的“文档”(数据返回从数据库中)正确。请记住,“文档”是一个数组,所以你需要这样引用它们:

router.get('/articles', function(req, res) { 
    Blog.find(function(err, docs){ 
     return res.render('blog/articles', { 
      title: docs[0].title, // Get the title for first entry 
      articles: docs[0].body // Get body for the first entry 
     }); 
    }); 
}); 

我硬编码数组的索引,但你可以使用一个循环从数组中获得每一个项目。

我不认为OP的解决方案解决了这个问题,因为...

默认情况下,编译模型时:

const someModel = mongoose.model('someModel', SomeSchema); 

猫鼬创建使用“someModel的名字并添加”集合s“,所以如果你检查你的数据库,你的集合应该是 显示为'someModels'。随着OP的解决方案:

{ collection: 'blog' } 

作为第二个参数创建博客模式

var blogSchema = new Schema(); 

默认行为是覆盖和您的收藏的名字会被你设置为收藏价值,在当这种情况下,“博客”。

你可以阅读更多关于它在Mongoose official docs 或在MDN - Node/Express/Mongoose