如何从mongoose返回多个文档并在html中显示

时间:2015-07-04 22:38:19

标签: node.js mongodb mongoose

每当我尝试在集合中返回多个文档并在我的网页上使用ejs引擎显示它时,我得到一个错误,即'date'属性无法读取但我在控制台日志中看到它返回了一系列结果与我的查询一致。如何使用ejs返回这些结果并将所有结果发布到网页上?我尝试在返回的结果数组上使用for循环,但它不起作用。有什么建议? 这是我服务器代码的一部分。

   app.get('/userprofile', isLoggedIn, function(req, res) {

        async.parallel([

            function(callback) {
                UserInfo.findOne({'infom.username' : req.user.local.username}, function(err,userinfo){
                    if(err)
                        throw err;

                    callback(null, userinfo);
                })
            },

            function(callback) {
                UserPost.find({'post.username' : req.user.local.username}, function(err, userpost) {
                    if(err)
                        throw err;
                    console.log(userpost);
                    callback(null, userpost);
                })
            }
            ],
            function(err, results){
                if(err)
                    throw err;

                var userinfo = results[0];
                var userpost = results[1];

                res.render('userprofile', {
                    userinfo : userinfo,
                    userpost : userpost,
                    user : req.user
                })
            })
    })

这是我的html文件的一部分。

<div id="userpost">
        <% if(userpost!=null) { %>

        <h3><%= user.local.username%></h3><h4><%= userpost.post.date%></h4>
        <h4><%= userpost.post.message%></h4>

        <% } %>
    </div>

这是我得到的错误。

TypeError: C:\javascript\views\userprofile.ejs:124
    122| <% if(userpost!=null) { %> 
    123| 
 >> 124| <h3><%= user.local.username%></h3><h4><%= userpost.post.date%></h4> 
    125| <h4><%= userpost.post.message%></h4> 
    126| 
    127| <% } %> 

Cannot read property 'date' of undefined
    at eval (eval at <anonymous> (C:\javascript\node_modules\ejs\lib\ejs.js:455:12), <anonymous>:45:41)
    at C:\javascript\node_modules\ejs\lib\ejs.js:482:14

用户架构

var mongoose = require('mongoose');


var postSchema = mongoose.Schema({

    post    :   {   
                username : String,
                message : String,
                date : Date
    }
})


module.exports = mongoose.model('UserPost', postSchema);

1 个答案:

答案 0 :(得分:0)

如果没有错误且Mongoose模型上的find方法将返回一个空数组,并且没有针对特定查询的结果轮。 在EJS(以及一般的JavaScript)中,空数组不等于null(即[] != null)。

这很可能导致你的ejs / html中的条件传递(<% if(userpost!=null) { %>)。但是,空数组显然没有UserPost模型的属性,因此userpost.post将是未定义的。

有几种方法可以防止这种情况发生。在EJS文件中添加更多条件,或者最好在渲染之前检查服务器代码中的“空”结果。