2017-12-28 23 views
-1

나는 mongodb와 Hapi.js를 처음 사용합니다. 읽기 요청을위한 API를 만들려고하지만 server.route에 처리기 메서드를 작성하는 방법을 모르겠습니다. 여기mongodh + hapi.js : 컬렉션이 정의되지 않았습니까?

내가 내 mongoclient이있는 게요로 구성한 방법은 다음과 같습니다

'use strict'; 
 

 
var MongoClient = require('mongodb').MongoClient; //using version 3.x 
 
var Hapi = require('hapi');//using v16 
 

 
var url = 'mongodb://****:****@ds131687.mlab.com:31687/learning_mongo'; 
 

 
var db; 
 

 
var server = new Hapi.Server(); 
 

 
server.connection({ 
 
    port:8080 
 
}); 
 

 
server.route([ 
 
    // Get tour list 
 
    { 
 
     method: 'GET', 
 
     path: '/api/tours', 
 
     handler: function(request, reply){ 
 
      collection.find().toArray(function(err,tours){ 
 
       reply(tours); 
 
      }); 
 
     } 
 
    }, 
 
    // Home page 
 
    { 
 
     method: 'GET', 
 
     path: '/', 
 
     handler: function(request, reply) { 
 
      reply("Hello world from Hapi/Mongo example."); 
 
     } 
 
    } 
 
]); 
 

 
var tours = function(db, callback) { 
 
    var collection = db.collection('tours'); 
 

 
    collection.find().toArray(function(err, docs){ 
 

 
      console.log(docs); 
 
      callback; 
 
     }); 
 
    
 
}; 
 

 
MongoClient.connect(url, function(err,client) { 
 
    
 
    server.start(function(err) { 
 
     
 
     tours(client.db('learning_mongo'), function(){ 
 
      
 
      console.log('Hapi is listening to http://localhost:8080'); 
 
      client.close(); 
 
      
 
     }); 
 
    });//end server 
 
    
 
})
는 홈페이지 경로에가는 것은 잘 작동하지만 나는 경로를 ./api/tours에 갈 때, 나는 터미널에서 다음 오류가 발생합니다.

Debug: internal, implementation, error 
 
    ReferenceError: Uncaught error: collection is not defined 
 
    at handler (/home/ubuntu/workspace/index.js:22:13) 
 
    at Object.internals.handler (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:101:51) 
 
    at request._protect.run (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:32:23) 
 
    at module.exports.internals.Protect.internals.Protect.run (/home/ubuntu/workspace/node_modules/hapi/lib/protect.js:60:12) 
 
    at exports.execute (/home/ubuntu/workspace/node_modules/hapi/lib/handler.js:26:22) 
 
    at each (/home/ubuntu/workspace/node_modules/hapi/lib/request.js:401:16) 
 
    at iterate (/home/ubuntu/workspace/node_modules/items/lib/index.js:36:13) 
 
    at done (/home/ubuntu/workspace/node_modules/items/lib/index.js:28:25) 
 
    at module.exports.internals.Auth.internals.Auth._authenticate (/home/ubuntu/workspace/node_modules/hapi/lib/auth.js:222:16) 
 
    at internals.Auth.authenticate (/home/ubuntu/workspace/node_modules/hapi/lib/auth.js:197:17)

컬렉션을 올바르게 정의하려면 어떻게해야합니까? 고맙습니다.

답변

-1

오류 메시지는 collection이 처리기 내부에서 벗어 났음을 의미합니다. tours function 안에 신고하십시오.

그러나 Mongoclient를 사용하여 데이터베이스와 컬렉션에 접근하는 방법에 약간의 오류가 있습니다.

일반적인 설정을 유지하면서 어떻게 작동하는지 보여 드리겠습니다. 이제 핸들러에서 db에 액세스 할 수 있음을 알 수 있습니다.

'use strict'; 
 

 
var MongoClient = require('mongodb').MongoClient; //using version 3.x 
 
var Hapi = require('hapi'); //using v16 
 

 
var url = 'mongodb://****:****@ds131687.mlab.com:31687/'; 
 

 
var db; 
 

 
var server = new Hapi.Server(); 
 

 
server.connection({ 
 
    port: 8080 
 
}); 
 

 
server.route([ 
 
    // Get tour list 
 
    { 
 
    method: 'GET', 
 
    path: '/api/tours', 
 
    handler: function(request, reply) { 
 
     db.collection('tours').find().toArray(function(err, tours) { 
 
     reply(tours); 
 
     }); 
 
    } 
 
    }, 
 
    // Home page 
 
    { 
 
    method: 'GET', 
 
    path: '/', 
 
    handler: function(request, reply) { 
 
     reply("Hello world from Hapi/Mongo example."); 
 
    } 
 
    } 
 
]); 
 

 
var tours = function(db, callback) { 
 
    db.collection('tours').find().toArray(function(err, docs) { 
 

 
    console.log(docs); 
 
    callback; 
 
    }); 
 

 
}; 
 

 
new MongoClient.connect(url, function(err, client) { 
 
    db = client.db('learning_mongo') 
 

 
    server.start(function(err) { 
 
    tours(db, function() { 
 

 
     console.log('Hapi is listening to http://localhost:8080'); 
 
     client.close(); 
 

 
    }); 
 
    }); //end server 
 

 
})

나는 이것은 단지 귀하의 측면에서 학습 예입니다 것으로 알고 있습니다. 그러나 아마 당신은 최신 hapijs 버전으로 시작하는 것을 고려하고 싶을 것입니다. 17. 더 큰 변화가 있었고, 이제 그 버전으로 시작하는 것이 더 쉬워졌습니다. 짧은 코드에는 이미 중첩 된 콜백이 많이 있습니다. 버전 17은 await/async 사용을 지원합니다.

+0

고마워요! 귀하의 예제를 적용하면 오류가 발생합니다. TypeError : null의 'db'속성을 읽을 수 없습니다. db = client.db ('learning_mongo') – redshift

+0

수정 됨 : 인증 문제 였으므로 URL이 정확한지 확인해야했습니다. 그것은 아닙니다, 그래서 나는 그것을 고쳤고 이제는 괜찮습니다! 감사! – redshift