简体   繁体   English

访问MongoDB后,ExpressJS对POST的响应未定义?

[英]ExpressJS response to POST is undefined after accessing MongoDB?

I'm making a web application using the MEAN framework and MVC design pattern. 我正在使用MEAN框架和MVC设计模式制作一个Web应用程序。 I am trying to perform a POST request from the Angular front-end for finding a document in my server-side MongoDB (version 2.4.9). 我正在尝试从Angular前端执行POST请求,以在服务器端MongoDB(版本2.4.9)中查找文档。 The console logs show that the query is successful, but when I try to send the response back to the client, the query result is undefined. 控制台日志显示查询成功,但是当我尝试将响应发送回客户端时,查询结果是不确定的。

I understand that NodeJS is asynchronous and uses callbacks, but I am having trouble understanding what is wrong with my code. 我知道NodeJS是异步的并且使用回调,但是我在理解我的代码出什么问题时遇到了麻烦。 I tried using returns and callbacks but I can't get it working. 我尝试使用return和callbacks,但无法正常工作。 I'm confused how to use the controller to access the model and have the controller ultimately send the response. 我很困惑如何使用控制器来访问模型并使控制器最终发送响应。

Here is my code to connect to the database (model): 这是我连接到数据库(模型)的代码:

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);
                });

        }
    })
}}

And here is my controller that sends the response: 这是我的控制器发送响应:

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 );

};

Client's post request: 客户的职位要求:

    // 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);
         });

Snippet for my express route: 我的快速路线的代码段:

var goodsServices = require('../controllers/gs-server-controller.js');
app.post('/recent', goodsServices.sendRecentPosts);

I have been struggling with this for a long time and searched the forum for solutions but could not find any. 我一直为此苦苦挣扎很长时间,并在论坛上搜索了解决方案,但找不到任何解决方案。 Thanks for any feedback. 感谢您的任何反馈。

I do not know why this question has not been answered yet. 我不知道为什么这个问题尚未得到回答。 When I faced the same problem, I learnt that the response to all DB queries are returned after the DB transaction is complete. 当我遇到相同的问题时,我了解到在数据库事务完成之后,将返回对所有数据库查询的响应。 Try placing db.close() within the success callback response of the find() call. 尝试将db.close()放入find()调用的成功回调响应中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM