2
I’m trying to make a generic repository, I’m using Mongodb for that, I tried to import it and use it with the property extends
other classes, but did not succeed.
What I need is to make the class available Repository
for all application controllers, and all features that require access to the database must be able to connect to the repository.
In this scenario what I tried:
// userSchema.js
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
// repository.js
class Repository {
constructor(dbCollection) {
this.dbCollection = dbCollection;
}
get(_id) {
return this.dbCollection.findById({ _id });
}
}
module.exports = Repository;
// user.repository.js
const Repository = require('./repository');
class UserRepository extends Repository {
constructor(user) {
super({
dbCollection: user
});
}
}
module.exports = UserRepository;
// UserController.js
const UserRepository = require('./user.repository.js');
class UserController {
async find(req, res) {
const user = await UserRepository.get(req.params.id);
return res.status(200).json(user);
}
}
module.exports = new UserController();
// mongo.js
const mongoose = require('mongoose');
const connectionOptions = {
useNewUrlParser: true,
useFindAndModify: false
};
class Database {
constructor() {
this.connect();
}
connect() {
return mongoose.connect(process.env.MONGO_URL, connectionOptions);
}
}
module.exports = new Database();
I also tried on the controller something like:
const UserRepository = require('./user.repository.js');
const schemaUser = require('./schemaUser');
class UserController {
async find(req, res) {
const test = new UserRepository(schemaUser)
const user = await test.get(req.params.id);
return res.status(200).json(user);
}
}
module.exports = new UserController();
In both cases without success. Like to do something similar to injection of dependencies.
I don’t remember, but
findById
receives an object? Wouldn’t be the_id
straight into the parameter in Mongoose:this.dbCollection.findById(_id);
?– Cmte Cardeal
And when you say "unsuccessful", Voce receives an error message or just nothing and returned in the query?
– Cmte Cardeal