I am currently working on a web application using the MEAN framework and following the MVC design pattern. My goal is to execute a POST request from the Angular front-end to search for a document in my server-side MongoDB (version 2.4.9). The console logs indicate that the query is successful, but I encounter an issue when trying to send the response back to the client as the query result turns out to be undefined.
While I understand that NodeJS operates asynchronously and utilizes callbacks, I'm facing difficulty in pinpointing the error within my code. Despite attempting to implement returns and callbacks, I have been unable to resolve the issue. I'm unsure of how to leverage the controller to access the model and ultimately transmit the response.
Below is my code snippet responsible for connecting to the database (model):
module.exports = {
readDocument : function(callback, coll, owner) {
// Establish connection to the 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);
//Retrieve document by owner
// Obtain documents collection
var collection = db.collection(coll);
// Locate 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 specified "find" criteria!');
}
// Close connection
db.close();
return callback(result);
});
}
})
}}
Additionally, here is the controller responsible for sending the response:
var model = require('../models/db');
exports.sendRecentPosts = function (req,res) {
// Connect to the DB
// Execute query for recent posts
// Close the connection
// Transmit the data to the client
var result = model.readDocument(dbCallback, "gs", "Mana");
res.end( result );
};
Example of the client's post request:
// Employ post method for secure queries
// Request recent posts for display purposes
$http.post('/recent').
success(function(responseData) {
$scope.testValue = responseData;
}).
error(function(responseData) {
console.log('Recent posts POST error. Received: ', responseData);
});
Snippet showcasing my express route:
var goodsServices = require('../controllers/gs-server-controller.js');
app.post('/recent', goodsServices.sendRecentPosts);
This has been a challenging issue for me, and despite conducting extensive research on the forum, no viable solutions have surfaced. Any feedback or suggestions would be greatly appreciated. Thank you.