2016-10-21 3 views
1

저는 REST API 요청을 처리하고 MongoDB 데이터베이스에서 데이터를 가져 오는 간단한 express.js 서버를 작성했습니다. 특정 끝점 ("localhost : 8081/api/getUserData")에 GET 요청을하면 promise chain이 원하는 방식으로 작동하지 않고 여전히 이해할 수 없습니다. 내가하지 않기 때문에 어떤 도움이 설명과 함께 더욱 평가 될 것입니다 : "[정의의 속성을 읽을 수 없습니다 'DB'형식 오류]"Express promise chain error

var MongoClient = require('mongodb').MongoClient; 
var express = require('express'); 
var app = express(); 
var rp = require("request-promise"); 
var cors = require('cors'); 

// use it before all route definitions 
app.use(cors({ origin: '*' })); 

/********************** REST API FUNCTIONS **********************/ 
app.get('/api/getUserData', function (req, res, next) { 
    var context = {}; 
    console.log("in api getUserData") 
    context.db_url = 'mongodb://localhost:27017/test'; 
    openDatabaseConnection(context) 
    .then(getAllUserLocations) 
    .then(closeDatabaseConnection) 
    .then(function (context) { 
     res.send(context.userLocations) 
    }) 
    .catch(function (error) { 
     console.log("ERROR :"); 
     console.log(error); 
    }) 
}) 
/********************** END REST API FUNCTIONS **********************/ 

function getAllUserLocations(context) { 
    context.db.collection("test").find().toArray().then(function (err, result) { 
    console.log("Received from db: " + result.length + " objects"); 
    context.userLocations = result; 
    return context; 
    }); 
} 

function openDatabaseConnection(context) { 
    console.log("Opening DB connection..."); 
    return MongoClient.connect(context.db_url) 
    .then(function (db) { 
     console.log("DB connection opened."); 
     context.db = db; 
     return context; 
    }) 
} 

function closeDatabaseConnection(context) { 
    console.log("Closing DB connection"); 
    return context.db.close() 
    .then(function() { 
     console.log("DB connection closed"); 
     return context; 
    }) 
} 

/********************** STARTING SERVER **********************/ 
var server = app.listen(8081, function() { 
    var host = server.address().address 
    var port = server.address().port 
    console.log("Githex server listening at http://%s:%s", host, port) 
}) 

:

은 내가 오류입니다 내가 잘못한 것을 이해하십시오.

감사합니다.

+1

'context'는'db_url' 속성을 가진 객체로 정의되었으므로'getAllUserLocations' 함수에서 사용할 때'db' 속성이 없습니다. – adeneo

+0

불행히도 그렇지 않습니다. 'db'속성을 지정하지 않고 다른 API 요청 처리기를 제공하는 코드를 제거했습니다. 방금 약속 체인 전에 db 속성을 추가하려고했지만 어느 쪽도 해결하지 못합니다. –

+0

맞아요, 오류는 'context'가 함수 중 하나에서 정의되지 않았으며 읽을 수 없음을 나타냅니다. 정의되지 않은 "*의 속성 'db'속성은 아마도 행 번호와 더 구체적인 정보가 어디서 왔는지에 따라 달라집니다. – adeneo

답변

0

첫 번째 주석에서 언급 한 @adeneo와 마찬가지로 db 속성이 누락되었습니다. 첫 번째 기능 봐 : 지금까지, 당신은 객체 위에 db_url 속성을 추가

    빈 객체로
  1. 당신의 설정 상황
  2. :

    app.get('/api/getUserData', function (req, res, next) { 
        var context = {}; 
        console.log("in api getUserData") 
        context.db_url = 'mongodb://localhost:27017/test'; 
        openDatabaseConnection(context) 
        .then(getAllUserLocations) 
        .then(closeDatabaseConnection) 
        .then(function (context) { 
         res.send(context.userLocations) 
        }) 
        .catch(function (error) { 
         console.log("ERROR :"); 
         console.log(error); 
        }) 
    }); 
    

    지금이 함수 내에서 라인을 통해 진행 당신은

    context = {db_url: "mongodb://localhost:27017/test} 
    
  3. openDatabaseConnection 함수에 컨텍스트 개체를 전달합니다.
  4. openDatabaseConnection 함수 내에서 컨텍스트 개체를 반환합니다. 이 새로운 반환 된 객체는 아무 데나 설정되지 않고 반환되며 결코 사용되지 않습니다. 반환 된 값을 사용하여 getuserlocation() 함수를 호출하려고합니다.

그래서 대신에 그냥

.then(function(context){getAllUserConnection(context);}) 

반환 된 값을 사용하고 당신이 그것을 사용하고 있는지 확인해야 할 것

.then(getAllUserConnection) 

를 호출.