Node.js Nodejs、Mongoose和Jade没有从数据库中获取数据
我一直在寻找我的问题,但甚至不知道问题在哪里 我得到的标题设置在我的路线,但没有数据从数据库 我的模型:Node.js Nodejs、Mongoose和Jade没有从数据库中获取数据,node.js,mongodb,express,mongoose,pug,Node.js,Mongodb,Express,Mongoose,Pug,我一直在寻找我的问题,但甚至不知道问题在哪里 我得到的标题设置在我的路线,但没有数据从数据库 我的模型: var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.Types.ObjectId; var blogSchema = new Schema({ title: { type: String, required: true }, author: { type:
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
我在页面上看到的唯一一个是
Blog_
那么我做错了什么
在错误文件中,它只说:“无法读取未定义的属性'title'”
所以物品对象没有设置…但是为什么
非常感谢
编辑1:
更改文章。文章标题不会更改任何内容
日志文件中的
GET /blog/articles HTTP/1.1 304 - - 3 ms
编辑2:
节点似乎没有从数据库中获取任何数据。。。
是的,有一个测试数据集;)
console.log()->
错误:空
文件:[]
解决方案作为答案发布获得解决方案
模型不对
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'});
必须在最后给收藏命名…因为它是用小写字母写的--
多假啊-永远不要再这样做了^ ^我知道这是一个非常老的问题,它被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
});
});
});
我正在对数组索引进行硬编码,但可以使用循环从数组中获取每个项
我认为OPs解决方案无法解决问题,因为
默认情况下,使用以下工具编译模型时:
const someModel = mongoose.model('someModel', SomeSchema);
mongoose使用“someModel”名称创建一个集合,并在末尾添加一个“s”,因此如果您检查数据库,您的集合应该
显示为“某些模型”。使用OP的解决方案:
{ collection: 'blog' }
作为创建博客模式时的第二个参数
var blogSchema = new Schema();
默认行为将被覆盖,集合的名称将是您设置为集合值的任何名称,在本例中为“blog”
您可以在中阅读更多关于它的信息
或者在中的模型部分,您可以将jade中的
文章.标题
更改为文章
,以便进行测试吗?我怀疑文章
未定义,因此解释了您的错误消息。请尝试console.log(docs)
。我知道没有标准,但你已经在我希望的某个地方发布了一个.connect
。