0

Using OOP with NodeJS and mongoose instead of callback hell.

I am using the following class.

Notice that I use getMember() with a callback. I wonder How can I bind it to callBack(err) properly without inside functions.

My expected result would be:

getMember(req, res) {
    var memberId = req.params.id;
    Member.findById(memberId, this.callBack);
}

enter code here

This is my class:

'use strict';
var mongoose = require('mongoose'),
    Member = mongoose.model('Members');

class Members {
    constructor(router) {
        this.router = router;
        this.registerRoutes();
    }
    callBack(err, task) {
        if(err)
            res.send(err);
        res.json(task);
    }
    registerRoutes() {
        this.router.get('/members', this.list_all_members.bind(this));
        this.router.get('/members/:id', this.getMember.bind(this));
        this.router.post('/members', this.create_a_member.bind(this));
    }
    getMember(req, res) {
        var memberId = req.params.id;
        Member.findById(memberId, function(err, task) {
            if(err)
                res.send(err);
            else
                res.json(task);
        });
    }
}

module.exports = Members;

Solution:

I came up with a solution.

My constructor function:

constructor() {
    this.callBack = (err, task, res) => {
        if(err)
            res.send(err);
        res.json(task);
    }
}

My callback using mongoose:

select(req, res) {
    // schemaDB is the mongoose schema.
    schemaDB.find({}, (err, task) => { this.callBack(err, task, res) } );
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
EpsilonTal
  • 437
  • 4
  • 20
  • Why don't you define functions in class as arrow functions? That way, you won't need to explicitly bind functions to class and you refer to properties of class using `this`. – Raeesaa May 19 '18 at 10:20
  • Can you explain, please? What do you mean by arrow functions? – EpsilonTal May 19 '18 at 10:21
  • You can read about arrow functions here: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4 – Raeesaa May 19 '18 at 10:24
  • Thanks, but that way I still repeat the same code for each function. I want to use OOP. – EpsilonTal May 19 '18 at 10:30
  • That way you would be able to define `getMember()` something like: `getMember = (req, res) => { var memberId = req.params.id; Member.findById(memberId, this.callBack); }`. – Raeesaa May 19 '18 at 10:32

0 Answers0