2016-06-06 3 views
0

이것은 첫 번째 게시물입니다. 친절 하구만. 열쇠를 기반으로 뚜렷한 데이터를 검색하려고합니다. 먼저 내 스키마 : 저장된 샘플몽구스, 약속 및 루프

var SampleSchema = mongoose.Schema({ 
 
     name: {type: String, index: true}, 
 
     _atId: {type: mongoose.Schema.ObjectId, ref: atHandler.ArrayTypes.Schema, index: true}, 
 
     factors: [{ 
 
      key: {type: String, index: true}, 
 
      value: {type: String, index: true} 
 
     }] 
 
    });

, 여러 가지 요소에 0이 될 것입니다. 나는 모든 키를 구별하고 각 키에 대해 고유 한 값을 가져와야하는 유스 케이스가있다.

{ 
     [ 
      { key: 'key1', values: [values] }, 
      { key: 'key2', values: [values] }, 
     ] 
    } 

하나가 (선호) 또는 몽구스 몽구스 조합이 하/nodejs 매우 유용 할 것이다 :

원하는 결과는 같을 것이다.

나는 시도했다 :

  • Promise.all()를
  • 몽구스 집계 쿼리가 I에 유래를 검색 가지고하지 않은 키

어디 쿼리

  • 몽구스 별개의 비슷한 질문을하거나 사람들이 나를 찾아내는 데 도움이 될만큼 가까워서 ... 누군가가 어떤 것을 찾으면 나는 그것들도 감사 할 것입니다 ...


    편집 : 다음은 실패한 시도입니다.

     .get('/:sgv/factors', function(req, res){ // get all the factors associated with this SGV since the client cannot work with data from different SGVs 
     
          // need to get distinct factors.key and then for each their collection of distinct values... 
     
          var sgv = sanitize(req.params.sgv); 
     
    
     
          log.debug('GET-samples-[%s]-factors', sgv); 
     
    
     
          sampleHandler.Samples 
     
           .distinct('factors.key') 
     
           .lean(true) 
     
           .exec() 
     
           .then(function (factors) { 
     
            function getValuesForKey(key){ 
     
             return sampleHandler.Samples 
     
              .distinct('factors.value', { 'factors.key': key}) 
     
              .exec() 
     
              .then(function(results){ 
     
               var p = new Promise(function(fullfill, reject){ 
     
                fullfill(results); 
     
               }); 
     
               console.log(results); 
     
    
     
    
     
               return p; 
     
              }) 
     
            } 
     
            function getValuesForKeys(keys){ 
     
             return Promise.all(keys.map(getValuesForKey)); 
     
            } 
     
    
     
            getValuesForKeys(factors) 
     
             .done(function(results){ 
     
            //  console.log(results); 
     
              res.status(200).send({keys: keys, values:results}); 
     
             }, function(err){ 
     
              console.log(err); 
     
              res.status(400).send({err: err}); 
     
             }); 
     
    
     
    
     
    
     
    
     
           }) 
     
           .catch(function (err) { 
     
            console.log('error: ' + err); 
     
            res.status(400).send({err: err}); 
     
           }); 
     
    
     
         })

    그 결과는 다음과 같다뿐만 아니라 근로자가 (클러스터를 사용) 사망있다. 스택 추적 또는 오류 메시지가 없습니다.

    ['blood','child','father','mother','tumor','433333','4444','4477hhjj','54','555','f2','m2','13','666','m1' ] 
     
    [ 'blood', 'child', 'father', 'mother', 'tumor', '433333', '4444', '4477hhjj', '54', '555', 'f2', 'm2', '13', '666', 'm1' ] 
     
    [ 'blood', 'child', 'father', 'mother', 'tumor', '433333', '4444', '4477hhjj', '54', '555', 'f2', 'm2' ] 
     
    [ 'blood', 'child', 'father', 'mother', 'tumor' ] 
     
    [ '433333', '4444', '4477hhjj', '54', '555', 'child', 'f2', 'm2' ] 
     
    [ '433333', '4444', '4477hhjj', '54', '555', 'child', 'f2', 'm2' ] 
     
    [ '433333', '4444', '4477hhjj', '54', '555', 'child', 'f2', 'm2' ] 
     
    [ '433333', '4444', '4477hhjj', '54', '555', 'child', 'f2', 'm2' ] 
     
    [ '433333', '4444', '4477hhjj', '54', '555', 'child', 'f2', 'm2', '13', '566', 'm1' ]
    은 다음과 같다 : 'F1', 'F2' ', F3', 'F4', 'F5 ","F6 ","F8 ",'커 '] 위의 값 중 일부는 각 키에 대해 다소 동일합니다. 모든 샘플 (스키마)이 같은 수의 키를 가지고있는 것은 아닙니다 ...

    Promise.all로 시도해 보았습니다. 나는 내가 인정해야하는 nodej와 나는 약속보다 익숙하지 않다. 나는 아직도 배우고있다.

  • +0

    에 오신 것을 환영합니다! Mongoose는 Node.js에서 실행됩니다. 그것들은 별개의 환경이 아닙니다. 또한 일부 시도에서 코드를 보여 주면 도움이 될 것입니다. 그래서 우리는 시작해서 당신에게 효과가없는 것을 알게 될 것입니다. –

    +0

    제안 해 주셔서 감사합니다. 나는 Mongoose가 NodeJs 안에서 돌아 다니는 것을 이해하지만 Mongoose와 Promise (내가 시도한 ...)의 결합이있을 수 있기 때문에 그것을 별도로 호출하고 싶었다. 나는 곧 코드 예제를 얻으려고 노력할 것이다. 나는 여러 가지 방법을 시도하고 그들 중 어느 것도 지키지 않았다 ... 내가 무엇을 할 수 있는지 보아라. –

    +0

    약속은 단지 자바 스크립트의 구조이다. 그것은 당신이 물건과 몽구스를 사용했다고 말하는 것과 같습니다. 그것은 고립 된 어떤 것도 의미하지 않습니다. 내가 말했듯이, 당신의 시도에서 어떤 코드를 보여주기 위해 질문을 편집 할 수 있습니까? –

    답변

    0

    다른 사람이 더 좋은 대답을 내놓으면 좋을 것입니다. 그래서 좋을 것 같습니다. 그렇다면, 내가 위에서 보여 몽고에서 입력 데이터를 가져다가 다음에 그것을 아래로 붕괴

     .get('/factors', function(req, res) { // get all the factors associated with this SGV since the client cannot work with data from different SGVs 
     
          // need to get distinct factors.key and then for each their collection of distinct values... 
     
          log.debug('GET-samples-factors'); 
     
    
     
          sampleHandler.Samples 
     
          .distinct('factors') 
     
          .lean(true) 
     
          .exec() 
     
          .then(function(data) { 
     
           var d = []; 
     
           for (var i = 0; i < data.length; i++) { 
     
           if (!d[data[i].key]) { 
     
            d[data[i].key] = new Set(); 
     
           } 
     
           d[data[i].key].add(data[i].value); 
     
           } 
     
           var f = []; 
     
           for (var key in d) { 
     
           if (d.hasOwnProperty(key)) { 
     
            f.push({ 
     
            key: key, 
     
            values: Array.from(d[key]) 
     
            }); 
     
           } 
     
           } 
     
           res.json(f); 
     
          }) 
     
          .catch(function(err) { 
     
           console.log('error: ' + err); 
     
           res.status(400).send({ 
     
           err: err 
     
           }); 
     
          }); 
     
         })
    ... 그들의 답을 변경할 수 있지만, 나는이 염두에 두어야 할 것이다 모든 샘플에서 동일하거나 다른 값의 다양한 조합을 검증하기 위해 아직 테스트하지 않았습니다 ...: 스택 오버플로

    [{ 
     
        "key": "f1", 
     
        "values": ["blood", "tumor", "m2", "13"] 
     
    }, { 
     
        "key": "f4", 
     
        "values": ["child"] 
     
    }, { 
     
        "key": "f2", 
     
        "values": ["father", "mother", "f2", "m1"] 
     
    }, { 
     
        "key": "f3", 
     
        "values": ["mother", "father", "child"] 
     
    }, { 
     
        "key": "f7", 
     
        "values": ["433333"] 
     
    }, { 
     
        "key": "f5", 
     
        "values": ["4444"] 
     
    }, { 
     
        "key": "f8", 
     
        "values": ["4477hhjj"] 
     
    }, { 
     
        "key": "f6", 
     
        "values": ["54"] 
     
    }, { 
     
        "key": "joker", 
     
        "values": ["555", "666"] 
     
    }]