TypeError:无法读取未定义节点js的属性'_id'

Posted

技术标签:

【中文标题】TypeError:无法读取未定义节点js的属性\'_id\'【英文标题】:TypeError: Cannot read property '_id' of undefined node jsTypeError:无法读取未定义节点js的属性'_id' 【发布时间】:2017-03-12 07:07:01 【问题描述】:

我正在关注 Adam Bretz 和 Colin J. Ihrig 的 FULL Stack javascript DEVELOPMENT WITH MEAN。当我进入第 8 章时,尝试插入在线 mongo 数据库时无法克服这个错误。我需要使用旧版本的节点吗?我查看了堆栈交换,但无法在所有建议的修复后使其工作...... 这是我的错误:

TypeError: Cannot read property '_id' of undefined
    at insertEmployees (/Users/kikocarisse/Desktop/NODESITES/chapter8/index.js:100:17)
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/index.js:195:5
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/index.js:79:7
    at Function.<anonymous> (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/lib/model.js:3369:16)
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/lib/model.js:1890:18
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/internal/parallel.js:35:9
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/node_modules/lodash/before.js:31:21
    at iteratorCallback (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/eachOf.js:52:13)
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/internal/onlyOnce.js:12:16
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/internal/parallel.js:32:13
    at apply (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/node_modules/lodash/_apply.js:15:25)
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/async/node_modules/lodash/_overRest.js:32:12
    at model.callbackWrapper (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/lib/model.js:1865:11)
    at next_ (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:89:34)
    at fnWrapper (/Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:186:8)
    at /Users/kikocarisse/Desktop/NODESITES/chapter8/node_modules/mongoose/lib/model.js:3369:16

这是我的代码:

"use strict";
var a = require('./a.js');
var b = new a(5);
var mongoose = require('./node_modules/mongoose');
var express = require('express');
var app = express();

var bodyParser = require('./node_modules/body-parser');
app.use(bodyParser.urlencoded(
  extended: true
));
app.route('/echo')
    .all((req,res)=>
        let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
        res.send(pars);
    );


var Schema = mongoose.Schema;
var db = mongoose.connection;
var dbUrl = 'mongodb://*****:******@******:*****/****';

var TeamSchema = new Schema(
  name: 
    type: String,
    required: true
  
);
var Team = mongoose.model('Team', TeamSchema);

var EmployeeSchema = new Schema(
  name: 
    first: 
      type: String,
      required: true
    ,
    last: 
      type: String,
      required: true
    
  ,
  team: 
    type: Schema.Types.ObjectId,
    ref: 'Team'
  ,
  image: 
    type: String,
    default: 'images/user.png'
  ,
  address: 
    lines: 
      type: [String]
    ,
    postal: 
      type: String
    
  
);

var Employee = mongoose.model('Employee', EmployeeSchema);


db.on('error', function () 
  console.log('there was an error communicating with the database');
);

function insertTeams (callback) 
  Team.create([
    name: 'Product Development'
  , 
    name: 'Dev Ops'
  , 
    name: 'Accounting'
  ], function (error, pd, devops, acct) 
    if (error) 
      return callback(error);
     else 
      console.info('teams successfully added')
      callback(null, pd, devops, acct);
    
  );


function insertEmployees (pd, devops, acct, callback) 
  Employee.create([
    name: 
      first: 'John',
      last: 'Adams'
    ,
    team: pd._id,
    address: 
      lines: ['2 Lincoln Memorial Cir NW'],
      postal: '20037'
    
  , 
    name: 
      first: 'Thomas',
      last: 'Jefferson'
    ,
    team: devops._id,
    address: 
      lines: ['1600 Pennsylvania Avenue', 'White House'],
      postal: '20500'
    
  , 
    name: 
      first: 'James',
      last: 'Madison'
    ,
    team: acct._id,
    address: 
      lines: ['2 15th St NW', 'PO Box 8675309'],
      postal: '20007'
    
  , 
    name: 
      first: 'James',
      last: 'Monroe'
    ,
    team: acct._id,
    address: 
      lines: ['1850 West Basin Dr SW', 'Suite 210'],
      postal: '20242'
    
  ], function (error, johnadams) 
    if (error) 
      return callback(error);
     else 
      console.info('employees successfully added');
      callback(null, 
        team: pd,
        employee: johnadams
      );
    
  )


function retrieveEmployee (data, callback) 
  Employee.findOne(
    _id: data.employee._id
  ).populate('team').exec(function (error, result) 
    if (error) 
      return callback (error);
     else 
      console.log('*** Single Employee Result ***');
      console.dir(result);
      callback(null, data);
    
  );


function retrieveEmployees (data, callback) 
  Employee.find(
    'name.first': /J/i
  , function (error, results) 
    if (error) 
      return callback(error);
     else 
      console.log('*** Multiple Employees Result ***')
      console.dir(results);
      callback(null, data);
    
  );


function updateEmployee (first, last, data, callback) 
  console.log('*** Changing names ***');
  console.dir(data.employee);

  var employee = data.employee;
  employee.name.first = first;
  employee.name.last = last

  employee.save(function (error, result) 
    if (error) 
      return callback(error);
     else 
      console.log('*** Changed name to Andrew Jackson ***');
      console.log(result);
      callback(null, data);
    
  );


mongoose.connect(dbUrl, function (err) 
  if (err) 
    return console.log('there was a problem connecting to the database!' + err);
  
  console.log('connected!');

  insertTeams(function (err, pd, devops, acct) 
    if (err) 
      return console.log(err)
    
    insertEmployees(pd, devops, acct, function (err, result) 

      retrieveEmployee(result, function (err, result) 

        retrieveEmployees(result, function (err, result) 

          updateEmployee('Andrew', 'Jackson', result, function (err, result) 
            if (err) 
              console.error(err);
             else 
              console.info('database activity complete')
            

            db.close();
            process.exit();
          );
        );
      );
    );
  );
);

【问题讨论】:

以后调试用; 1.查看错误消息的堆栈跟踪文件和行号; 2. 导航到该行的第一个文件; 3. 如果您的标识符紧接在它之前,则记录所有; 4. 如果出现意外情况,要么添加逻辑以将其捕获,要么返回堆栈跟踪的一级并重复 【参考方案1】:

在第 100 行,devops 变量是 undefined,这就是您收到错误的原因。请参阅insertTeams 函数,这是您在创建团队时首先获得 devops 价值的地方。

这可能就是为什么你的创建回调是这样的:function (error, pd, devops, acct) 但看到Mongoose docs,它传递一个数组作为创建的第二个参数。

试试这个:

function insertTeams (callback) 
  Team.create([
    name: 'Product Development'
  , 
    name: 'Dev Ops'
  , 
    name: 'Accounting'
  ], function (error, teams) 
    if (error) 
      console.log(error);
      return callback(error);
     else 
      console.info('teams successfully added')
      callback(null, teams[0], teams[1], teams[2]);
    
  );

请注意,现在它获取了一个数组并将其元素传递给回调,还请注意我添加了一个日志,如果有错误,您可以看到它发生的位置。

此外,如果您阅读错误日志并指出错误发生的行内容是什么,这会有所帮助,请注意我们这里没有行号,这使得查找错误更加困难。

【讨论】:

以上是关于TypeError:无法读取未定义节点js的属性'_id'的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取未定义的属性“地址”

(节点:14808)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“角色”

这将返回未定义:(节点:3196)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“myArray”

(节点:2724)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“第一个”

(节点:10388)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“缓存”

(节点:4044)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“缓存”