【问题标题】:Mongoose Map type incompatible with TypeScript typeMongoose Map 类型与 TypeScript 类型不兼容
【发布时间】:2022-01-22 01:35:33
【问题描述】:

我有以下模型架构接口:

import { Document } from 'mongoose';

export interface ILog {
  tags: { [key: string]: string }[];
}

export interface ILogDocument extends ILog, Document {}

还有架构:

const logSchema = new Schema<ILogDocument>({
  tags: { type: Map, of: String },
});

所以我的架构出现以下类型错误:

TS2322: Type '{ type: MapConstructor; of: StringConstructor; }' is not assignable to type 'SchemaDefinitionProperty<{ [key: string]: string; }[]> | undefined'.

我想使用正确的类型定义,我尝试了type: Schema.Types.Mixed 及其作品,但是有没有更好的方法来为tags: { [key: string]: string }[] 指定猫鼬类型?

【问题讨论】:

    标签: node.js typescript mongodb mongoose mongoose-schema


    【解决方案1】:

    { [key: string]: string }[] 不完全是 Map。您可以使用 TS 中的 Map 类型。

    import { Document, Schema } from 'mongoose';
    
    export interface ILog {
      tags: Map<string, string>;
    }
    
    export interface ILogDocument extends ILog, Document {}
    
    const logSchema = new Schema<ILogDocument>({
      tags: { type: Map, of: String }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2019-09-06
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2020-12-11
      • 1970-01-01
      相关资源
      最近更新 更多