0

我设置了 Mongo,我所做的只是在 index.jade 中,循环浏览一份餐食列表。

--app.js--

/** * 模块依赖。*/

var express = require('express')
mongoose = require('mongoose')
, routes = require('./routes')
, meal = require('./routes/meal')
, http = require('http')
, path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/new', meal.new);

app.get('/meals', meal.getMeals)
app.post('/meals', meal.add)

app.get('')
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

--meals.js--


var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/nutritionTracker")

var MealSchema = new mongoose.Schema({
mealId: Number,
mealType: String,
mealDetails: String
}),

Meals = mongoose.model('Meals', MealSchema);


/*
* New meal.
*/

exports.new = function(req, res){
res.render('new');
};

/*
* Insert new meal.
*/

exports.add = function(req, res){

var meal = req.body;

new Meals({
mealId: 1,
mealType: meal.mealType,
mealDetails: meal.mealDetails
}).save(function (err, docs) {
if (err) res.render("Error")
});
res.render('new');
};

/*
* Get all meals.
*/

exports.getMeals = function(req, res){
Meals.find({}, function(err, docs) {
res.render('index', { meals: docs });
});
};

--index.jade--

扩展布局

block content
table.table.table-striped
thead
tr
th Meal Type
th Meal Details
tbody
each meal in meals
tr 
td #{meal.type}
td #{meal.details}

a(href="/new", class="btn btn-primary btn-lg") Add Meal

我不断收到此错误:

类型错误:...\views\index.jade:10 8| 餐点详情 9| tbody > 10| 每餐中餐 11| 12| td #{meal.type} 13| td #{meal.details} 无法读取未定义的属性“长度”

有任何想法吗?

4

2 回答 2

0

不确定您发布的内容,但您可能想确保您的查询实际上带回了您的期望。err您在不使用的回调中传递了一个变量。

试试这个,让我知道它带来了什么:

exports.getMeals = function(req, res){
    Meals.find({}, function(err, docs) {
        console.log(err, docs);
        if(err) return res.send(500, {
            error: err
        });
        res.render('index', { meals: docs });
    });
}

Cannot read property 'length' of undefined可能是玉抱怨它无法循环遍历结果,因为它们无效(数组)。

于 2013-10-17T23:23:54.010 回答
0

问题可能出在您的渲染代码中,您的代码在其中使用翡翠修改了响应。这是将变量传递给jade的地方,我猜想最近对jade和express的更新可能会导致问题。

当我更新我的翡翠和快递时,我遇到了这些错误。我查看了玉存储库中的示例。在最新的jade@0.26.3 和express@3.4.8 中,服务器会渲染一个包含如下数据的jade 文件:

server.get('/', function(req, res) {
  return res.render('index.jade', {
    title: 'Blog',
    description: 'Your Page Description',
    users: users
  });
});

使用return res.render('index.jade', {meals:meals});as 是与旧版本的区别。

于 2014-01-14T23:34:30.087 回答