【问题标题】:TypeError when I try to run mt Node.js application当我尝试运行 mt Node.js 应用程序时出现 TypeError
【发布时间】:2019-01-25 10:00:01
【问题描述】:

我正在尝试从 REST API Development With Node.js working 中获取示例程序。当我尝试运行它时,出现此错误:

TypeError: Cannot read property 'indexOf' of undefined
    at translateTypeToJs (/Users/paulcarron/Documents/Books/REST API Development With Node.js/lib/db.js:93:8)
    at translateComplexType (/Users/paulcarron/Documents/Books/REST API Development With Node.js/lib/db.js:58:21)
    at _.each (/Users/paulcarron/Documents/Books/REST API Development With Node.js/lib/db.js:83:13)
    at Function._.each._.forEach (/Users/paulcarron/Documents/Books/REST API Development With Node.js/node_modules/underscore/underscore.js:191:9)
    at Object.getModelFromSchema (/Users/paulcarron/Documents/Books/REST API Development With Node.js/lib/db.js:76:5)
    at module.exports (/Users/paulcarron/Documents/Books/REST API Development With Node.js/models/book.js:7:21)
    at module.exports (/Users/paulcarron/Documents/Books/REST API Development With Node.js/models/index.js:3:30)
    at Object.<anonymous> (/Users/paulcarron/Documents/Books/REST API Development With Node.js/lib/db.js:21:35)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)

我已经通过代码甚至检查了GitHub project,但看不出我做错了什么。从上面的日志看,它似乎在默认情况下调用translateTypeToJs。我已经用书中的内容检查了这一点,并且完全一样。我该如何解决这个问题?

这是我的 lib/db.js 代码:

const config = require("config"),
  _ = require("underscore"),
  mongoose = require("mongoose"),

  Schema = mongoose.Schema;

let obj = {
  cachesModels: {},
  getModelFromSchema: getModelFromSchema,
  model: function(mname) {
    return this.models[mname]
  },
  connect: function(cb) {
    mongoose.connect(config.database.host + "/" + config.database.dbname);
    this.connection = mongoose.connection;
    this.connection.on('error', cb);
    this.connection.on('open', cb);
  }
}

obj.models = require("../models/")(obj);

module.exports = obj;

function translateComplexType(v, strType) {
  let tmp = null;
  let type = strType || v['type'];
  switch(type) {
    case 'array':
      tmp = [];
      if(v['items']['$ref'] != null) {
        tmp.push({
          type: Schema.ObjectId,
          ref: v['items']['$ref']
        });
      } else {
        let originalType = v['items']['type'];
        v['items']['type'] = translateTypeToJs(v['items']['type']);
        tmp.push(translateComplexType(v['items'], originalType));
      }
    break;
    case 'object':
      tmp = {};
      let props = v['properties'];
      _.each(props, (data, k) => {
        if(data['$ref'] != null) {
          tmp[k] = {
            type: Schema.ObjectId,
            ref: data['$ref']
          }
        } else {
          tmp[k] = translateTypeToJs(data['type']);
        }
      });
    break;
    default:
      tmp = v;
      tmp['type'] = translateTypeToJs(type);
    break;
  }
  return tmp;
}


/**
 * Turns the JSON Schema into a Mongoose schema
 */
function getModelFromSchema(schema){
  let data = {
    name: schema.id,
    schema: {}
  }

  let newSchema = {};
  let tmp = null;
  _.each(schema.properties, (v, propName) => {
    if(v['$ref'] != null) {
      tmp = {
        type: Schema.Types.ObjectId,
        ref: v['$ref']
      }
    } else {
      tmp = translateComplexType(v) //{}
    }
    newSchema[propName] = tmp;
  });
  data.schema = new Schema(newSchema);
  return data;
}


function translateTypeToJs(t) {
  if(t.indexOf('int') === 0) {
    t = "number";
  }
  return eval(t.charAt(0).toUpperCase() + t.substr(1));
}

【问题讨论】:

  • console.log(v['items']['type']) 在调用 translateTypeToJs 之前检查它记录的内容
  • 在第 93 行: if(t.indexOf('int') === 0) 我想您需要先检查 t 是否为空或正确的类型,如 if(t &amp;&amp; t.indexOf('int') === 0)
  • @McRist 您的提示让我意识到我的架构存在问题。一旦我进行了排序,我就解决了这个问题。

标签: javascript node.js rest api typeerror


【解决方案1】:

如果translateComplexType(v) //{} 行注释的意思是v 在该行可以是一个空对象,那么:

  • 线let type = strType || v['type']可以使type === undefined
  • translateTypeToJs(undefined) 调用将在tmp['type'] = translateTypeToJs(type) 上进行(从而引发TypeError)

我建议进行以下修复:

let type = strType || v['type'] || 'undefined'

【讨论】:

    【解决方案2】:

    在这种情况下,问题是由于架构结构不正确造成的。修复后,我不再遇到此问题。

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多