0

我正在为 nodejs 使用“mongodb”驱动程序。我正在尝试将 ttl 的可选参数添加到此现有方法中:

public async createIndex(index: any, unique: boolean): Promise<void> {
    await this.collection.createIndex(index, { unique });
}

有没有比这更优雅的方法:

public async createIndex(index: any, unique: boolean, ttl: number): Promise<void> {
    await ttl ? this.collection.createIndex(index, { unique, ttl }) : this.collection.createIndex(index, { unique });
}

我读到将 null 传递给可选参数会使其行为怪异。

4

3 回答 3

3

为了使其更简洁,您可以为 mongodb 传入一个带有选项(唯一和 ttl)的对象。

public async createIndex(index: any, opts: { unique: boolean, ttl?: number }): Promise<void> {
    await this.collection.createIndex(index, opts);
}
于 2020-12-15T06:33:23.657 回答
0

一种选择是有条件地定义内联属性:

public async createIndex(index: any, unique: boolean, ttl: number) {
    await this.collection.createIndex(index, {
      unique,
      ...(ttl ? { ttl } : {})
    });
}

请注意,如果 TS 可以自动推断返回值,则无需注意返回值。(如果你愿意,你可以,但在大多数情况下它没有帮助。)

另一种选择是使用条件运算符定义参数,可以提前或内联在参数列表中:

public async createIndex(index: any, unique: boolean, ttl: number) {
    const param = ttl ? { unique, ttl } : { ttl };
    await this.collection.createIndex(index, param);
}
于 2020-12-15T06:26:37.347 回答
0

在这种情况下,无需检查参数“ttl”

public async createIndex(index: any, unique: boolean, ttl?: number): Promise<void> {
    await this.collection.createIndex(index, { unique, ttl });
}

代码“{ unique, ttl }”表示“{ unique: unique, ttl: ttl }”,当“ttl”未定义时,结果为“{ unique: unique, ttl: undefined }”,没有错误

于 2020-12-15T06:37:03.190 回答