2014-02-15 1 views
1

내 모델은노드 ORM 절약 중첩 된 객체

  • 아이디어는 아이디어 하나가 사용자
  • 위치가 한 방향
  • 위치 한 보안
  • 위치 하나를 가지고 있음했다
  • 많은 위치가 본질적으로 아이디어 (아이디어의 반대에는 많은 직책이 있습니다)

나는 d 'Q'는 그런 방식으로 프로그램하기위한 많은 노드 - 오옴 (node-orm) 기능을 약속한다. 그래서는 DB (MySQL의)이 지속하는 가장 좋은 방법 찾기 위해 애 쓰고 있어요 ... 지금 qFind 등이다

을 찾을 : 여기

User.qGet(1004).then(function(user) { 

    var newIdea = new Idea({ 
     'openedOn': new Date() 
    }) 

    newIdea.setUser(user, console.log) 

    Idea.qCreate(newIdea).then(function(idea) { 
     _.each(positions, function(position) { 

      Security.qFind({ticker: position.ticker}).then(function(securities){ 
       var security = securities[0] 

       Direction.qFind({direction: position.direction}).then(function(directions){ 
        var direction = directions[0] 
        var newPosition = Position({ 
         'weight': 1 
        }) 

        newPosition.setIdea(idea, console.log) 
        newPosition.setDirection(direction, console.log) 
        newPosition.setSecurity(security, console.log) 

        console.log(JSON.stringify(newPosition)) 

       }) // Direction.qFind    
      }) // Security.qFind 
     }) // _.each 

     console.log(JSON.stringify(idea)) 
     res.send(idea) 
    }) // Idea.qCreate 

}) // User.find 

을 내 문제가

  1. 그것은되어 있습니다 작동 안함.

[Error: ER_BAD_NULL_ERROR: Column 'directionId' cannot be null]

문제는 2.이 중첩 된 객체 저장에 대한 올바른 접근 방식인가 ...이 객체의 세 가지 외래 키를 설정해야한다 : 나는 아이디어를 설정하면, 나는 오류가?

답변

0

나는 약속의 사용을 수용하기로 결정하고, Q 라이브러리

1 단계 내 ORM 모델의 흥미로운 방법에 q를 nbind를 추가. 예를 들어 :

model = db.models.direction 
model['qFind'] = Q.nbind(model['find'], model); 

2 단계는 내 모델로 인스턴스 메소드를 첨가 하였다 : 나는 특성을 저장하는 내부 성공 방법을 정의하는이 단계에서

setDirectionByName: function(direction) { 

    var _this = this; 
    var internalSuccess = function(directions) { 
     _this.direction = directions[0] 
     _this.directionId = directions[0].id 
     return directions 
    } 

    return { 
     then: function(externalSuccess, externalFail) { 
      var success = _.compose(externalSuccess, internalSuccess) 
      Direction.qFind({direction: direction}).then(success, externalFail) 
     } 
    } 
} 

및 활용 가능성을 반환 조성물 총 성공 기능 ('다음'호출로 전달되는 하나의 내부 내 모델 중 하나를 형성하는

3 단계 :. 요청을 처리 데이터

여기
User.qGet(1004).then(function(user) { 

    var newIdea = new Idea({ 
     'openedOn': new Date() 
    }) 

    newIdea.setUser(user, function(){}) 

    Idea.qCreate(newIdea).then(function(idea) { 

     var positionPromises = _.map(positions, function(position) { 

      var newPosition = Position({ 
       'weight': 1 
       ,'ideaId': idea.id 
      }) 

을 저장 나는 외래 키를 설정하고 Position.create가 비동기 적으로 약속 반환과 함께 쫓겨 전에 그들이, 완료 될 때까지 기다립니다.

  return Q.all([ 
        newPosition.setDirectionByName(position.direction) 
        , newPosition.setSecurityByTicker(position.ticker) 
       ]).then(function(noop) { 
        //newPosition.setIdea(idea) 
        return Position.qCreate(newPosition) 
       }) 
     }) // _.map 

SO 다음 순위 오브젝트 약속의 배열.여기 나는 그 (것)들에게 모두를 채우기 위하여 기다릴 것이다, 클라이언트에게 결과를 돌려 보내기 전에

 Q.all(positionPromises).then(function(positions){ 
      console.log('RESULTS of POSITION Promises') 
      //console.log(JSON.stringify(positions)) 

      //This doesn't seem to work as expected 
      //idea.setPositions(positions, function(e, o){ }) 

      // kludge it 
      idea.positions = positions 



      console.log(JSON.stringify(idea)) 
      console.log('/RESULTS of POSITION Promises') 
      res.send(idea) 

     }) 

     console.log('FALL THROUGH') 
    }) // Idea.qCreate 

}) // User.find 
0

하나의 해결책은

var newPosition = Position({ 
    'weight': 1 
    ,'ideaId': idea.id 
    ,'directionId': direction.id 
    ,'securityId': security.id 
}) 

Position.create(newPosition, function(e, i){ 

}) 

문제는 /Associations/One.js가 연결을 설정할 때 저장 호출이다 ID를 설정하는 것입니다.