2015-10-08 80 views
0

我正在使用MEAN框架和MVC設計模式製作Web應用程序。我正嘗試從Angular前端執行POST請求,以在我的服務器端MongoDB(版本2.4.9)中查找文檔。控制檯日誌顯示查詢成功,但當我嘗試將響應發送回客戶端時,查詢結果未定義。訪問MongoDB後ExpressJS對POST的響應是未定義的?

我明白,NodeJS是異步的,並使用回調,但我無法理解我的代碼有什麼問題。我嘗試使用返回和回調,但我無法得到它的工作。我很困惑如何使用控制器訪問模型並讓控制器最終發送響應。

這裏是我的代碼連接到數據庫(模型):

module.exports = { 

readDocument : function(callback, coll, owner) { 

    // Connect to database 
    MongoClient.connect("mongodb://localhost:27017/tradingpost", function(err, db) { 
      if (err) { 
      console.log("Cannot connect to db (db.js)"); 
      callback(err); 
      } 
     else { 
       console.log("Connected to DB from db.js: ", db.databaseName); 

       //Read document by owner 

       // Get the documents collection 
       var collection = db.collection(coll); 

       // Find document 
       collection.find({owner: owner}).toArray(function (err, result) { 
        if (err) { 
         console.log(err); 
        } else if (result.length) { 
         console.log('Found:', result); 
        } else { 
         console.log('No document(s) found with defined "find" criteria!'); 
        } 

       // Close connection 
       db.close(); 

       return callback(result); 
       }); 

     } 
    }) 
}} 

這裏是我的控制器發送響應:

var model = require('../models/db'); 
exports.sendRecentPosts = function (req,res) { 

    // Connect to the DB 
    // Run query for recent posts 
    // Close the connection 
    // Send the data to the client 
    var result = model.readDocument(dbCallback, "gs", "Mana"); 
    res.end(result); 

}; 

客戶的POST請求:

// Use post for secure queries 
    // Need recent posts for display 
    $http.post('/recent'). 
     success(function(responseData) { 
      $scope.testValue = responseData; 
      }). 
     error(function(responseData) { 
      console.log('Recent posts POST error. Received: ', responseData); 
     }); 
我的快遞路線的代碼段:
var goodsServices = require('../controllers/gs-server-controller.js'); 
app.post('/recent', goodsServices.sendRecentPosts); 

我一直在爲此苦苦掙扎很久,搜索論壇的解決方案,但找不到任何。感謝您的任何反饋。

回答

0

我不知道爲什麼這個問題還沒有得到解答。當我遇到同樣的問題時,我瞭解到在數據庫事務完成後,將返回對所有數據庫查詢的響應。嘗試將db.close()放在find()調用的成功回調響應中。