事起缘由, 最近一直在做重构系统的工作, 数据库使用的是 mongodb, orm 使用的是 nestjs/mongoose, 原来使用的是 typegoose, 后面切换成了 nestjs/mongoose 切换理由再起文论述, 此处展示一些 mongoose 的类型问题

构建 query 或者 filter

相关 issue nestjs/mongoose

期待:

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;
}

实际:

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;
}

一些考虑和决舍

使用 typescript 很重要的一个目的之一就是为了减少 coding 过程中容易出现的错误, 提高编码效率, 而且 query 或者 filter 的构建属于 查询 非常重要的一部分, 理想情况下使用一种 orm 最少能满足基本的使用需求, 这里的需求就隐含包括 类型提供, 明确, 以及 约束, 也是之前没有注意到这块, 如何针对该问题进行补救, 换 orm ? Prima 应该没这种问题吧, TypeOrm 虽然问题比较多, 但是也没这种问题, 但是 TypeOrmMongodb 支持确实不是很好, 那就 Prima 了? 宁要基本体验没问题, 不惜重写 Schema 及相关代码!!!

此问题, 不管使用 nestjs/mongoose 或者 typegoose, mongoose 都会出现, 本质上就是 mongoose 的类型问题