Background: Recently, I have been working on refactoring a system. The database used is
mongodb, and theormisnestjs/mongoose. Previously,typegoosewas used, but it has since been switched tonestjs/mongoose. The reasons for this switch will be discussed in a separate article. Here, I will highlight some type-related issues withmongoose.
Building a query or filter
Related issue nestjs/mongoose
Expected:
public toFilter() {
const filter: FilterQuery<SampleTypeDocument> = {};
if (this.code) filter.code = this.code; // filter.code has type
if (this.category) filter.category = this.category; // same below
if (this.storageType) filter.storageType = this.storageType; // same below
if (this.name) filter.name = this.name; // same below
// has ts error
filter.xxx = {};
return filter;
}
Actual:
public toFilter() {
const filter: FilterQuery<SampleTypeDocument> = {};
if (this.code) filter.code = this.code; // ok can jump where be defined but no type limit
if (this.category) filter.category = this.category; // same below
if (this.storageType) filter.storageType = this.storageType; // same below
if (this.name) filter.name = this.name; // same below
// no error
filter.xxx = {};
return filter;
}
Some Considerations and Trade-offs
One of the primary purposes of using typescript is to reduce errors that are prone to occur during coding, thereby improving coding efficiency. Moreover, constructing query or filter is a very important part of querying. Ideally, using an orm should at least meet basic usage requirements. This implicitly includes type provision, clarity, and constraints. This aspect was previously overlooked. How should we remedy this issue? Should we switch orm? Prisma probably doesn't have this issue, right? TypeOrm has many issues, but it doesn't have this specific problem either. However, TypeOrm's support for Mongodb is indeed not very good. So, should we go with Prisma? It's better to have a solid basic experience, even if it means rewriting the Schema and related code!!!
This issue will occur whether using nestjs/mongoose or typegoose. Essentially, it is a typing issue with mongoose
Comments (0)
No comments yet. Be the first to leave one!