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.