开发者问题收集

NodeJS、MongoDB、Jade/Pug - 无法读取 Apache 上未定义的属性“length”(localhost 有效)

2017-09-13
1012

我在服务器(由 KingHost 托管)中连接我的应用程序时遇到了一些问题。 在本地机器上,它运行完美 在服务器上,我做的一件事就是将数据库从 localhost 更改为服务器,并将端口从 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)

但在 localhost 上它运行完美... 数据库是相等的(见下图) 数据库服务器(大),数据库 localhost(prompt)

代码(服务器和 localhost 之间的变化)

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

其他可能重要的事项:

  • node 版本:6.11.1
  • npm 版本:3.10.10
  • mongodb 版本(从服务器上的 npm 安装):2.2.31 package.json 的依赖项
"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 }
2个回答

更新

根据 mongodb 错误代码 ,13 对应于 Unauthorized 。您可以查看 MongoDB 未授权查询 - 代码 13 以修复它。


原始答案

Cannot read property 'length' of undefined

它清楚地表明在 undefined 变量上调用了 .length 。因此,我怀疑您的结果[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],
        ...
    });
});
Sridhar
2017-09-16

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

Vengatesh Subramaniyan
2018-03-22