NodeJS无法读取属性'长度'未定义的。

时间:2015-10-21 05:01:45

标签: node.js mongodb express

以前被引导到How to get a callback on MongoDB collection.find(),但这并没有解决问题。

这是来自使用nodejs的build 10项目的nodeblog分配。之前已经下载了教师代码并得到了错误。之后,将所有内容包装在.toArray中,但仍然收到相同的错误。

TypeError: /Users/Dropbox/projects/nodeblog/views/addpost.jade:16
    14|             label Category
    15|             select.form-control(name='category')
  > 16|                 each category, i in categories
    17|                     option(value='#{category.title}') #{category.title}

Cannot read property 'length' of undefined

这是addpost.jade文件

extends layout
block content
    h1=title
        .form-group
            label Title:
            input.form-control(name='title', type='text')
        .form-group
            label Category
            select.form-control(name='category')
                each category, i in categories
                    option(value='#{category.title}') #{category.title}

这是posts.js文件

router.get('/add', function(req, res, next){
    var categories = db.get('categories');

    categories.find({},{}, function(err, categories){
        categories.toArray(function(err, catArray){
            res.render('addpost',{
                "title": "Add Post",
                "categories": categories
            });
    });
});
});

router.post('/add', function(req, res, next){
    // Get Form Values
    var title       = req.body.title;
    var category    = req.body.category;
    var body        = req.body.body;
    var author      = req.body.author;
    var date        = new Date();


    // Form Validation
    req.checkBody('title','Title field is required').notEmpty();
    req.checkBody('body', 'Body field is required');

    // Check Errors
    var errors = req.validationErrors();

    if(errors){
        res.render('addpost',{
            "errors": errors,
            "title": title,
            "body": body
        });
    } else {
        var posts = db.get('posts');

        // Submit to DB
        posts.insert({
            "title": title,
            "body": body,
            "category": category,
            "date": date,
            "author": author,
            "mainimage": mainImageName
        }, function(err, post){
            if(err){
                res.send('There was an issue submitting the post');
            } else {
                req.flash('success','Post Submitted');
                res.location('/');
                res.redirect('/');
            }
        });
    }
});

module.exports = router;

0 个答案:

没有答案