SO here is my route.js file, which handles all the routes.
// Import post controller
const PostController = require('../controllers/post');
// Call post controller for API
router.post('/posts', PostController.create);
And then there is post.js file in controllers, which exports Post class.
const PostModel = require('../models/post');
class Post
{
async create ()
{
response = {};
let posts = await PostModel.find({});
response.additionalInfo = this.getAdditionalInfo();
res.status(200).send({response});
}
getAdditionalInfo ()
{
// returns some data for users and something
}
}
module.exports = new Post();
Now My question is how do i call getAdditionalInfo()
from create method? because if i try this.getAdditionalInfo()
i get undefined
error.
This is how create
is being used:
router.post('/posts', PostController.create);
With your
router.post('/posts', PostController.create);
, router.post
is accepting a function named create
as a callback. This means that when it's invoked, for example, if the internal code for router.post
looks something like this:
(url, callback) => {
on(someevent, () => {
callback();
});
}
The calling context is missing. It's not calling PostController.create()
, it's just calling someCallbackVariableName()
. So, without a calling context, the this
inside of create
is undefined
as a result.
Instead, either pass a function that invokes create
with the proper calling context:
router.post('/posts', () => PostController.create());
Or use .bind
to explicitly set the calling context to PostController
:
router.post('/posts', PostController.create.bind(PostController));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With