Undefined when accessing class attributes in NodeJS

1

Good afternoon guys, I 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 it returns an undefined message that I do not know the reason, I replicated the same implementation in PHP and it worked fine. / p>

The following is the code below:

Model using 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);

Model repository

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 is returned Can not read 'model' of undefined property, but if I give a console.log in this.model in the constructor it is displayed in the terminal. I would like to understand the reason for the error, thank you in advance.

    
asked by anonymous 13.02.2018 / 17:59

2 answers

0

There may also be a bind problem, that is, when a function of another lib happens to exist inside the class it still has its own scope, it happens a lot in Javascript that you have to use this but the this class you built sometimes is not the external function this you are using because it may be it has a this itself. How to solve: you can add an arrow function instead of using the normal function, since the arrow function in ES6 is a synthetic function that treats this question of this:

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 you do not have the es6 transpilators on your node you can 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 resolve are also valid. :)

    
16.02.2018 / 01:16
0

I'd have to do some testing before I 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 asynchronicity of the data to see if your command is not running before the data reaches you. Take a look here

link

link

    
14.02.2018 / 18:14