简体   繁体   中英

ExpressJS response to POST is undefined after accessing MongoDB?

I'm making a web application using the MEAN framework and MVC design pattern. 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). 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. I tried using returns and callbacks but I can't get it working. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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