I have a BaseRepository with the main methods that mongoose provides like this:
class BaseRepository {
constructor(model) {
this.model = model;
}
async get(id) {
return this.model.findById(id);
}
async find(filter) {
return this.model.find(filter);
}
async sort(filter) {
return this.model.sort(filter)
}
....
}
And so I'm using a dependency injection pattern with awilix so I can use them like this on my service layer, for example my userRepository:
this.userRepository.find({})
And everything works fine, the problem lies when I try to chain my repository methods like this:
this.userRepository.find({}).sort({createdAt: -1})
I get the following error:
this.userRepository.find(...).sort is not a function
I'll gladly accept a few suggestions on how to make this work. Thanks!
CodePudding user response:
Remove the async
modifier. When a method/function is marked as async
, it will always return a Promise
. In your case, you want to return the object returned by mongoose's find
, which is a querying API object.