2016-06-25 2 views
0

Adam Bretz &의"MEAN을 사용한 전체 스택 JavaScript 개발 "의 8 장의 예제를 통해 작업하고 Colin Ihrig와 그 책의 코드는 작동하지 않습니다. (아마도 의도적으로) 완성 된 것처럼 보입니다. Ive는 인터넷 검색 및 StackOverflow 검색을 디버깅하는 데 많은 시간을 보냈습니다. 이 스크립트는 insertEmployee와 bails가 될 때까지 올바르게 실행할 수 있습니다. insertEmployee 인수 (pd, devops, acct)에 대한 인수가 어떻게 설정되는지 파악할 수 없습니다. 나는 콜백 지옥에 갇혔다."TypeError : 정의되지 않은 '_id'속성을 읽을 수 없음

기본적으로 저는 입니다. 노드를 사용하여 MongoDb를 채우십시오.

If I set the insertEmployee function to use pd._id for all the employees its fine, but using devops._id or acct._id always results in the error below

*TypeError: Cannot read property '_id' of undefined 
    at insertEmployees (/Users/Bluemagma/Sites/NodeJS Example Application/database/humanresourcesSchema.js:111:17) 
    at /Users/Bluemagma/Sites/NodeJS Example Application/database/humanresourcesSchema.js:199:3 
    at /Users/Bluemagma/Sites/NodeJS Example Application/database/humanresourcesSchema.js:62:4 
    at Function.<anonymous> (/Users/Bluemagma/Sites/NodeJS Example Application/node_modules/mongoose/lib/model.js:3352:16) 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/mongoose/lib/model.js:1863:18 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:726:13 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:52:16 
    at done (/Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:246:17) 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:44:16 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:723:17 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/async/lib/async.js:167:37 
    at model.callbackWrapper (/Users/Bluemagma/Sites/NodeJS Example Application/node_modules/mongoose/lib/model.js:1841:11) 
    at next_ (/Users/Bluemagma/Sites/NodeJS Example Application/node_modules/hooks-fixed/hooks.js:89:34) 
    at fnWrapper (/Users/Bluemagma/Sites/NodeJS Example Application/node_modules/hooks-fixed/hooks.js:186:18) 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/mongoose/lib/model.js:3352:16 
    at /Users/Bluemagma/Sites/NodeJS Example Application/node_modules/mongoose/lib/model.js:228:5* 

는 Heres는 humanresourcesSchema.js

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var db = mongoose.connection; 
var dbUrl = 'mongodb://localhost/humanResources'; 

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 damn 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 sucessfully added sir!'); 
      callback(null, pd, devops, acct);   
     } 
    }); 
} 

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 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 sir!'); 
     callback(null, { 
     team: pd, 
     employee: johnadams 
     }); 
    } 
    }) 
} 

function updateEmployee (first, last, data, callback) { 
    console.log('*** Changin 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); 
     } 
    }); 
} 

function removeTeams() { 
    console.info("deleting all previously added teams sir!"); 
    Team.remove({}, function(error, response) { 
     if(error) { 
      console.error("tried to delete all teams but " + error); 
     } 
     console.info("done deleting all teams sir!"); 
    }); 
} 

function removeEmployees() { 
    console.info("deleting all previously added employees sir!"); 
    Employee.remove({}, function(error, response) { 
     if(error) { 
      console.error("tried to delete all employees but " + error); 
     } 
     console.info("done deleting all employees sir!"); 
    }); 
} 

mongoose.connect(dbUrl, function (err) { 
    if (err) { 
     return console.log('there was a problem connecting to the database sir!' + err); 
    } 
    console.log('connected to the database sir!'); 
    removeTeams(); 
    removeEmployees(); 
    insertTeams(function (error, pd, devops, acct) { 
     if (error) { 
      return console.log(error); 
     } 
     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 sir!"); 
        } 

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

내 코드는 당신의 도움 노드와 몽고 천재 주셔서 감사합니다! 콜백에 대해 더 많이 알기를 기대합니다.

+0

필자는 pd가 아닌 다른 인수를 사용하여 처음으로 Im은 "Team : devops._id"라는 줄을 추가해야합니다. Team : pd._id로 설정하면 문제가 없습니다. – bluemagma

답변

1
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 sucessfully added sir!'); 
      callback(null, pd, devops, acct);   
     } 
    }); 
} 

여기 콜백은 나에게 의심스러워 보입니다. Team.create()에 단일 인수로 배열을 전달하므로 콜백은 function(err, results)으로 호출됩니다. 여기서 결과는 삽입 된 문서가 들어있는 배열입니다.

callback(null, pd, devops, acct);과 같이 콜백을 호출하면 오류가 null이되고 pd가 결과 배열이되고 devops 및 acct는 정의되지 않습니다.

팀을 개별 인수로 Team.create에 전달할 수 있으며 콜백이 여러 인수로 호출되거나 그대로두고 코드를 배열을 처리하도록 조정할 수 있습니다.

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 sucessfully added sir!'); 
      callback(null, pd, devops, acct);   
     } 
    }); 
} 

몇 절묘한 콘솔 : 여기

Mongoose examples.

또는 (희망)은 "쟁반 내 일했고 난 그냥 두 브래킷을 제거했다"버전입니다.log()의 변수를 잃어버린 곳을 찾는 데 많은 도움이 될 수 있습니다.

+0

감사합니다. 나는 이것을 분명히 시험해보고 몽구스 문서에 대한 링크를 게시 해 주셔서 감사합니다! – bluemagma

+0

당신이 제안한대로 나는 괄호를 꺼냈다. 나는 아직도 일하는 것이지만 디버깅을 도와 준 것에 대해 안개가 낀다! – bluemagma

+0

내가 링크 된 문서에는 "개별 문서 전달"과 "배열 전달"의 차이점을 보여주는 예가 회색 상자에 있습니다. 나는 당신이 그 차이점을 이해할 수있을 것이라고 생각합니다. 또한 나는 대답을 받아들이는 stackoverflow의 프로세스를 지적 할 수도 있습니다 :) http://stackoverflow.com/help/accepted-answer – marton

0

insertTeams 함수에서 오류가 발생한다는 느낌이 들었습니다.

오류가있는 콜백 함수 (insertEmployees)를 호출하면 함수는 오류가 발생하면 오류를 catch하거나 처리하지 않습니다. 대신 콜백을 호출하고 오류 자체를 인수로 전달합니다. insertEmployees는 오류 처리가 없으므로 시작하기 전에 오류가 발생했는지 확인하지 않습니다. 따라서 devops의 _id 특성을 호출하려고하면 함수가 호출 될 때 정의되지 않았으므로 devops는 정의되지 않습니다. 따라서 JS 오류가 발생합니다.

자세한 정보는 insertTeams에서 오류가 발생하면 로깅 해보십시오.

편집 : 문제가 여전히 insertEmployees가 콜백 (오류)과 함께 호출되고 있다고 가정합니다. 오류가 _ 생하므로 _id 필드에 액세스 할 수 있으므로 최소한 undefined가 리턴됩니다. 그러나 다른 인수는 정의되어 있지 않습니다. 함수에 전달되지 않기 때문에 정의되지 않은 객체의 필드에 액세스하려고하므로 _id 필드에 액세스하자 마자 오류가 발생합니다. .

+0

그건 의미가있어, 나를 도와 줘서 고마워! – bluemagma

관련 문제