NodeJS,MongoDB,Jade/Pug - 无法读取 Apache 上未定义的 属性 'length'(本地主机有效)

NodeJS, MongoDB, Jade/Pug - Cannot read property 'length' of undefined on Apache(localhost works)

我在服务器(由 KingHost 托管)中连接我的应用程序时遇到一些问题。 在本地机器上,它完美运行 在服务器上,我做的一件事是将数据库从本地主机更改为服务器,并将端口从 3000 更改为我的服务器...

当我 运行 服务器上的应用程序时,我得到:

TypeError: /home/rsracingufrgs/apps_nodejs/views/index.jade:316
    314|                         h3.section-heading Capitão
    315|                 .row
  > 316|                     each membro, i in capitao
    317|                         .col-sm-4
    318|                             .team-member
    319|                                 img.mx-auto.rounded-circle(src='/img/team/#{membro.imagem}', alt='#{membro.nome}')

Cannot read property 'length' of undefined
    at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:1755:31)
    at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:1888:4)
    at eval (eval at <anonymous> (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:218:8), <anonymous>:6670:22)
    at res (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:219:38)
    at Object.exports.renderFile (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:380:38)
    at Object.exports.renderFile (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:370:21)
    at View.exports.__express [as engine] (/home/rsracingufrgs/apps_nodejs/node_modules/jade/lib/index.js:417:11)
    at View.render (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/view.js:127:8)
    at tryRender (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/application.js:640:10)
    at EventEmitter.render (/home/rsracingufrgs/apps_nodejs/node_modules/express/lib/application.js:592:3)

但是在本地主机上它运行得很好...... 数据库是相等的(见下图)

代码(服务器和本地主机之间的变化)

var db = monk('localhost:27017/rsracingufrgs') //localhost
//var db = monk('mongodb.rsracingufrgs.com.br/rsracingufrgs01'); //server

var porta = 3000 // localhost
//var porta = 21031 //server

对数据库的调用:

router.get('/', function (req, res, next) {

    const db = req.db;
    const async = require("async")

    const names = ['capitao',...]

    const collections = names.map(name => db.get(name) )

    const functions = collections.map(collection => {
        return done => collection.find( {}, done )
    })

    async.series( functions, (err, results) => {
        // "results" is now an array containing [ docs1, docs2, .. ]
        res.render('index', {
            env: env,
            capitao: results[0],
            ...
        });
    })
});

Jade 代码(在本地主机上工作):

        .row
            each membro, i in capitao
                .col-sm-4
                    .team-member
                        img.mx-auto.rounded-circle(src='/img/team/#{membro.imagem}', alt='#{membro.nome}')
                        h4 #{membro.nome}
                        p.text-muted #{membro.curso}
                        ul.list-inline.social-buttons
                            li.list-inline-item
                                a(href="mailto:#{membro.email}")
                                    i.fa.fa-envelope

其他可能重要的事情:

"dependencies": {
    "async": "^2.5.0",
    "body-parser": "^1.18.1",
    "connect-ensure-login": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "dotenv": "^4.0.0",
    "express": "^4.15.4",
    "express-session": "^1.15.5",
    "jade": "^1.11.0",
    "logger": "0.0.1",
    "mongo": "^0.1.0",
    "mongodb": "^2.2.31",
    "mongoose": "^4.11.11",
    "monk": "^6.0.4",
    "morgan": "^1.8.2",
    "passport": "^0.4.0",
    "passport-auth0": "^0.6.0",
    "path": "^0.12.7",
    "request": "^2.81.0"
  }

编辑:使用@Sridhar 提供的调试代码,我得到了以下结果:

{ MongoError: not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }
    at Function.MongoError.create (/home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/error.js:31:11)
    at queryCallback (/home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/cursor.js:212:36)
    at /home/rsracingufrgs/apps_nodejs/node_modules/mongodb-core/lib/connection/pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }',
  ok: 0,
  errmsg: 'not authorized on rsracingufrgs01 to execute command { find: "capitao", filter: {}, projection: {} }',
  code: 13 }

更新

根据 mongodb error codes, 13 corresponds to Unauthorized. You can check MongoDB not authorized for query - code 13 进行修复。


原回答

Cannot read property 'length' of undefined

它明确指出 .length 是在 undefined 变量上调用的。所以,我怀疑你的结果 [0] 会是 undefined。如果您记录结果,您将了解有关该问题的更多信息。

'use strict';

let _ = require('lodash');

....

async.series(functions, (err, results) => {
    if (err || _.isUndefined(results)) {
        //general error handling
        console.log(err);
        return res.render('index', {
            env: env,
            capitao: []
        });
    }
    res.render('index', {
        env: env,
        capitao: _.isUndefined(results[0]) ? [] : result[0],
        ...
    });
});

你的值未定义,所以只能通过那个错误。因此,请在访问该变量的长度 属性 之前检查该值是否未定义。