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.
I used the bind approach and it worked perfectly, thank you very much.
– Gabriel Guedes