Chhatrasal Singh Bundela Chhatrasal Singh Bundela - 2 months ago 16
Node.js Question

how to access methods of one object in other module?

I am using this statement in my router.js file.

var script = ('./script');
router.get('/getCustomer/:id',function (request, response) {
console.log('get method called.......');
script.getSingleCustomer(mongo.DATABASE, response);
});


and in my script.js

var Customer = require('./customerModel'); //my schema is defined in this script
module.exports = {
getSingleCustomer : function(database, request, response){
// var user = new Customer({
// _id: request.params.id
// });
database.collection('customer').findOne({}, function (error, results) {
if (error) {
console.log(error);
response.json({statusCode: 400, statusData: 'The customer is not registered...', responseData: [results]});
}
console.log(results);
response.json({statusCode: 200, statusData: 'Success', responseData: [results]});
});
}
};


Right now I am not implementing any id based query, I just need to access the database and send the result to android app and I am getting the following error:

TypeError: Cannot read property 'json' of undefined
at C:\Users\chhat\Upcomers Tech\customer\script.js:17:21
at handleCallback (C:\Users\chhat\Upcomers Tech\node_modules\mongodb\lib\utils.js:120:56)
at C:\Users\chhat\Upcomers Tech\node_modules\mongodb\lib\collection.js:1417:5
at handleCallback (C:\Users\chhat\Upcomers Tech\node_modules\mongodb\lib\utils.js:120:56)
at C:\Users\chhat\Upcomers Tech\node_modules\mongodb\lib\cursor.js:682:5
at handleCallback (C:\Users\chhat\Upcomers Tech\node_modules\mongodb-core\lib\cursor.js:171:5)
at nextFunction (C:\Users\chhat\Upcomers Tech\node_modules\mongodb-core\lib\cursor.js:682:5)
at C:\Users\chhat\Upcomers Tech\node_modules\mongodb-core\lib\cursor.js:593:7
at queryCallback (C:\Users\chhat\Upcomers Tech\node_modules\mongodb-core\lib\cursor.js:232:18)
at C:\Users\chhat\Upcomers Tech\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)


Please help me to send the response from the script.js.
I am developing a node.js server with mongodb for android app, so suggest me some server design structure, as I am new in backend development.

Answer Source

You are calling the function with two arguments

script.getSingleCustomer(mongo.DATABASE, response);

But the function expects 3

getSingleCustomer: function(database, request, response)

So request will hold what actually is the response, and response will be undefined in getSingleCustomer(). To fix that, either don't make the function expect request (preferably, as you don't use it in the function either way

getSingleCustomer: function(database, response)

Or call it with three arguments (senseless in this case).

script.getSingleCustomer(mongo.DATABASE, request, response);

And fix the typo in function(databse, response), it's database