2012-04-24 5 views
1

내 js 파일이 작동하지 않는 스키마와 API를 설명합니다. 명령 줄 도구를 통해이 작업을 수행하면 ... 스키마가 매우 간단하며 간단한 find 명령을 구현했습니다.mongoose를 사용하여 노드 스크립트를 통해 mongodb 레코드를 저장할 수 없습니다.

'use strict' 

var util = require('util'); 
var bcrypt = require('bcrypt'); 
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var validatePresenceOf = function(value){ 
    return value && value.length; 
}; 

var toLower = function(string){ 
    return string.toLowerCase(); 
}; 

var SportsStandings = new Schema({ 
    'sport' : { type : String, 
       validate : [validatePresenceOf, 'a sport is required'], 
       set : toLower 
      }, 
    'league' : { type : String, 
       validate : [validatePresenceOf, 'a league is required'], 
       set : toLower 
      }, 
    'division' : { type : String, 
       validate : [validatePresenceOf, 'a division is required'], 
       set : toLower 
      }, 
    'teamName' : { type : String, 
       validate : [validatePresenceOf, 'a teamName is required'], 
       set : toLower 
      }, 
    'wins' : { type : Number, min: 0, 
       validate : [validatePresenceOf, 'wins is required'], 
      }, 
    'losses' : { type : Number, min: 0, 
       validate : [validatePresenceOf, 'losses is required'], 
      } 
}); 

SportsStandings.statics.findTeamRecord = function(sport, league, 
                division, teamName, 
               cb) { 
    return this.find({'sport' : sport, 'league' : league, 
        'division' : division, 'teamName': teamName}, cb); 
}; 

SportsStandings.statics.findBySport = function(sport, cb) { 
    return this.find({'sport' : sport}, cb); 
}; 

module.exports = mongoose.model('SportsStanding' , SportsStandings); 

여기가

'use strict' 

var util = require('util'); 
var mongoose = require('mongoose'); 
var db = mongoose.connect('mongodb://localhost/mydb'); 
var SportsStanding = require('../schemas/SportsStandings'); 

var record = new SportsStanding({ 
      'sport' : 'mlb', 
      'league' : 'AL', 
      'divison' : 'east', 
      'teamName' : 'New York Yankees', 
      'wins' : 10, 
      'losses' : 1}); 

record.save(function(err) { 
    console.log('error: ' + err); 
    SportsStandings.find().all(function(arr) { 
    console.log(arr); 
    console.log('length='+arr.length); 
    }); 
}); 

process.exit(); 
+0

당신이보고있는 어떤 오류? 작동하지 않는다고 말하면 문제 진단에 도움이되는 결과물이 있습니까? –

+0

아무 반응이 없습니다. 명령 줄에서 node : node sportsStandings.js를 사용하여 프로그램을 실행하면 mongo 명령 줄 도구를 사용하여 말할 수있는 한 오류가없고 데이터베이스에 커밋 된 것이 없습니다. mongo 명령 줄을 사용하여 db.sportsStandings.insert (....) 작업을 수행하면 ... – SPODOG

답변

1

로 프로그래밍 할 때 기억하시기 바랍니다 ..... 위의 수출 객체를 인스턴스화하고이 모델에 저장 명령을 수행하려고 간단한 노드 스크립트입니다 node.js를 사용하려면 이벤트 중심 프로그래밍 스타일에 매우주의해야합니다. 코드에 문제가있는 것은 외부 실행 수준에서 process.exit()을 호출한다는 것입니다. record.save(...)을 호출하면 즉시 외부 실행 수준으로 제어가 돌아가고 저장이 실행되거나 저장 콜백의 코드가 허용되지 않습니다.

이 문제를 해결하려면 가장 가까운 콜백 함수의 끝으로 process.exit()을 이동하고 예상 한 결과를 확인해야합니다.

예제를 실행하면 수정해야 할 몇 가지 오타 및 실수가 있습니다. SportStanding(s) 모델 변수의 철자를 확인하고 그것이 어디서나 일치하는지 확인하십시오. 또한 모델의 find()은 콜백이 필요하며 데이터베이스의 모든 레코드를 반환합니다 (두 번째 매개 변수 - 오류 플래그가 첫 번째 임). 따라서 all() 연결 호출이 필요하지 않습니다. 당신이처럼 보이는 결국해야 당신의 저장 기능에 대해 원하는 :

record.save(function(err) { 
    console.log('error: ' + err); 
    SportsStandings.find(function(err, arr) { 
     console.log(arr); 
     console.log('length='+arr.length); 
     process.exit(); 
    }); 
}); 
+0

고맙습니다. 고쳐 주셔서 감사합니다. – SPODOG

관련 문제