node.js - 无法读取未定义的属性 'title'。表达

标签 node.js mongodb express

您好,我正在开发 nodejs express 应用程序。我得到异常,不知道为什么。一切似乎对我来说都很完美。我的异常如下所示:

 500 TypeError: C:\Nodejs\NodejsBlog\apps\blog/views/postdetail.jade:23<br/> 21| .col- md-12 <br/> 22| .posts <br/> > 23| h3= post.title <br/> 24| p=post.body <br/> 25| p tag:      <br/> 26| i=post.tag <br/><br/>Cannot read property 'title' of undefined
21| .col-md-12
22| .posts
> 23| h3= post.title
24| p=post.body
25| p tag:
26| i=post.tag
Cannot read property 'title' of undefined
at eval (eval at (C:\Nodejs\NodejsBlog\node_modules\jade\lib\jade.js:152:8), :221:59)
at C:\Nodejs\NodejsBlog\node_modules\jade\lib\jade.js:153:35
at Object.exports.render (C:\Nodejs\NodejsBlog\node_modules\jade\lib\jade.js:197:10)
at Object.exports.renderFile (C:\Nodejs\NodejsBlog\node_modules\jade\lib\jade.js:233:18)
at View.exports.renderFile [as engine] (C:\Nodejs\NodejsBlog\node_modules\jade\lib\jade.js:218:21)
at View.render (C:\Nodejs\NodejsBlog\node_modules\express\lib\view.js:76:8)
at Function.app.render (C:\Nodejs\NodejsBlog\node_modules\express\lib\application.js:504:10)
at ServerResponse.res.render     (C:\Nodejs\NodejsBlog\node_modules\express\lib\response.js:798:7)
at C:\Nodejs\NodejsBlog\apps\blog\routes.js:64:14
at callbacks (C:\Nodejs\NodejsBlog\node_modules\express\lib\router\index.js:164:37)

这里是 app.post 代码:

app.get('/Post/:id',function(req,res){
    var postdata;
    var comments;
    Post.findOne({_id:req.params.id},function(err, docs){
            if(docs) {
                postdata=docs;  
                console.log('Gönderi bulundu');
                console.log(docs);
                console.log(postdata);
                console.log(postdata.title);
            } else {

                console.log('Gönderi bulunamadı');
            }
        });

        Comment.findOne({postid:req.params.id},function(err, docs){
            if(docs) {
                console.log('Yorum bulundu');
                console.log(docs);
            } else {
                comments=docs;  
                console.log('Yorum bulunamadı');
            }
        });

    return res.render(__dirname+"/views/postdetail",{
            title: 'adfasdf',
            stylesheet: 'postdetail',
            post:postdata,
            comments:comments
            });
});

我的看法:

extends ../../../views/bloglayout
block js
script(type='text/javascript')
    $(function() {
        $("#commentform" ).submit(function( event ) {
            alert( "Handler for .submit() called." );
            $.ajax({
                url: '/Post/Comment/',
                type: "POST",
                data: $('#commentform').serialize(),
                success: function(response){
                alert('Yorum Kaydedildi');
                }
            }); 
            event.preventDefault();
        });
    });

block content
.row
    .col-md-12
        .posts
            h3=post.title
            p=post.body
            p tag:
                i=post.tag
            p Anahtar Kelimeler:
                b=post.keywords
        .row
            .col-md-4
                h5 Yorum Yap
                  form#commentform(role='form',action='/Post/Comment', method='post')
                            input(type='hidden',name='comment[postid]',value=postdata._id)
                        .form-group
                            input.form-control(type='email',name='comment[email]',placeholder='E-posta adresi')
                        .form-group
                            input.form-control(type='text',name='comment[website]', placeholder='Website')
                        .form-group
                            textarea.form- control(type='text',name='comment[content]', placeholder='Yorum')
                        button.btn.btn-  default(type='submit') Ekle
                -comments.forEach(function(comment) {
                .well
                    p
                        b=comment.content
                    p=comment.email
                -})

我还检查了我的 mongodb。有数据。我不知道为什么 'title' 属性是 'undefined' 不知道。

最佳答案

这是一个竞争条件问题。从 MongoDB 中提取的两个函数是异步的,因此对 res.render() 的调用发生在 DB 在每个函数的相应回调中返回数据之前。您需要嵌套每个函数,以便它们可以访问正确的上下文。见下文:

app.get('/Post/:id', function (req, res, next){
  Post.findOne({_id:req.params.id},function(err, postData){
    if (err) return next(err);  

    Comment.findOne({postid:req.params.id},function(err, comments){
      if (err) return next(err);

      return res.render(__dirname+"/views/postdetail",{
        title: 'adfasdf',
        stylesheet: 'postdetail',
        post:postData,
        comments:comments
      });

    });
  });
});

但是,随着嵌套越深,您会发现这会变得非常困惑。为了防止这种情况,您可以使用控制流库,如 caolan/async

Side Note:

You're Jade is looking to iterate over a comments array and you are returning a single doc from MongoDB (assuming you are using the mongoose module). You will want to change your Mongoose function from findOne() to simply find() so that mongoose can return an array of docs with the proper postid.

编辑:


Vinayak Mishra 指出您可以使用 Express 的路由中间件作为在路由中施加控制流的一种方式也是正确的。这是一个例子:

// Use the app.param() method to pull the correct post doc from the database.
// This is useful when you have other endpoints that will require work on
// a Post document like PUT /post/:postid
app.param('postid', function (req, res, next, id) {

  Post.findById(id, function (err, post) {
    if (err) return next(err);
    if (!post) return next('route');
    req.post = post;
  });

});

app.get('/post/:postid',
  // -- First route middleware grabs comments from post doc saved to req.post
  function (req, res, next) {
    Comment.find({ postid: req.post.id }, function (err, comments) {
      if (err) return next(err);
      req.comments = comments;
      next();
    });
  },
  // -- This route middleware renders the view
  function (req, res, next) {
    res.render('/postDetail', {
      // ... list locals here ...
    });
  }
);

关于node.js - 无法读取未定义的属性 'title'。表达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20411459/

相关文章:

javascript - Node/ express /Nunjucks : TypeError: Cannot use 'in' operator to search for 'x' in 'y'

javascript - 尝试设置输入 node.js puppeteer 的值时出现未定义错误

javascript - 如何控制从 Node 中的流发起的异步http客户端请求的数量?

node.js - 如何组织我的规范文件?

java - Spring MongoDB - 查找两个日期之间的文档

node.js - 如何将 AWS lambda 函数变成自己的 https 端点?

node.js - Node mongodb : Error: connection closed due to parseError

c# - Mongo C# 驱动程序和 ObjectID JSON 字符串格式

python - 如何在没有 map/reduce 的情况下转换大型 Mongodb 集合中的每个文档?

node.js - Node Express从404文件请求中区分404页面请求