Undefined when accessing class attributes in Nodejs

Asked

Viewed 462 times

1

Good afternoon, you guys, was developing an api with Node and Mongo using express and Mongoose and tried to implement the Pattern Repository, but when accessing the attributes of a class returns a Undefined message that I do not know the reason, replicated the same implementation in PHP and worked well.

Follow the code below:

Model using the Mongoose

import mongoose from 'mongoose';
const { Schema } = mongoose;

const Pokemon = new Schema({
  name: {
    type: 'String',
    required: 'Name is required',
  },
  attack: {
    type: 'Number',
    required: 'Attack is required',
  },
  defense: {
    type: 'Number',
    required: 'Defense is required',
  },
  image: {
    type: 'String',
    required: 'Image is required',
  },
});
export default mongoose.model('Pokemon', Pokemon);

Repository of the model

import BaseRepository from '../repositories/BaseRepository';
import Pokemon from '../models/Pokemon';

class PokemonRepository extends BaseRepository {
  constructor() {
    super(Pokemon);
  }
}

export default PokemonRepository;

Repository base

class BaseRepository {
  constructor(model) {
    this.model = model;
  }
  save(req, res) {
    //Ao fazer qualquer referência a this.model o erro é retornado.
    res.status(201).json({ pokemon: 'save' });
  }
}

export default BaseRepository;

When I try to access the model attribute in the Baserepository file it is returned Cannot read Property 'model' of Undefined, but if I give a console.log in this.model in the constructor it is displayed in the terminal. I would like to understand why the mistake, I thank you in advance.

2 answers

0

I’d have to run some tests first to get it right, but you can

class Quadrado extends Poligono {
  constructor(comprimento) {
    // super chama o construtor da classe pai que vai atribuir comprimento para
    // os atributos comprimento e altura herdados pela nossa classe filha Quadrado  
    super(comprimento, comprimento);
    // Nas classes filhas, super() deve ser chamado antes de usar o this. Sem ele 
    // vai ocorrer um erro de referência. O this agora se refere a classe filha Quadrado
    this.nome = 'Quadrado';
  }

  // os atributos a seguir são herdados da classe pai Poligono: altura, comprimento e area.

  get area() {
    return this.altura * this.comprimento;
  }

  set area(valor) {
    this.area = valor;
  } 
}

But it’s also worth checking the data asymchronicity to see if your command isn’t running before the data gets to you. Take a look here

https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

0


There may also be a bind problem, that is, when a function of another lib comes into existence within the class it still has its own scope, It happens a lot in Javascript of you having to use this but this of the class that you sometimes built is not the this of the external function that you are using because it may be it has this itself. How to solve: you can add an Arrow Function instead of using the normal function, as the Arrow Function in ES6 is a synthetic function that addresses this issue of:

class BaseRepository {
  constructor(model) {
    this.model = model;
  }
  save = (req, res) => {
    //Ao fazer qualquer referência a this.model o erro é retornado.
    res.status(201).json({ pokemon: this.model });
  }
}

export default BaseRepository;

Or if you prefer, and/or not have with the es6 transpilators on your Node you can make a bind in your constructor:

class BaseRepository {
  constructor(model) {
    this.model = model;
    this.save = this.save.bind(this)
  }
  save(req, res) {
    //Ao fazer qualquer referência a this.model o erro é retornado.
    res.status(201).json({ pokemon: this.model });
  }
}

export default BaseRepository;

All two ways to solve are also valid. :)

  • I used the bind approach and it worked perfectly, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.