TypeScript结合Mongoose执行findOne查询报string无法赋值给Condition类型错误
问题出在自定义文档类型GameModel的定义逻辑完全混淆了两类结构:
- Mongoose Schema 构造时传入的配置对象结构(比如
{type: String, unique: true}是告诉Mongoose如何构建集合索引、执行字段校验的配置项) - 业务文档实际存储的字段值类型(标题字段实际存储的是字符串,并非那个配置对象)
Mongoose的查询参数类型会基于文档字段的TS类型生成Condition<T>结构,即支持传入字段本身类型,或是对字段做范围、模糊匹配的操作符。由于当前代码中GameModel的每个字段类型都直接复用了Schema的配置结构,导致TypeScript推导findOne的查询参数类型时,会要求title字段的传入值必须匹配带type/unique/required属性的对象,而非普通字符串,最终触发Type 'string' is not assignable to type 'Condition<...>'的类型校验报错。
除此之外还存在一个可运行性问题:findOne这类静态查询方法是挂载在model()返回的Model实例上的,直接用new Schema()生成的Schema实例调用该方法本身无法正常执行。
1. 修正GameModel的字段类型定义
将原有的Schema配置结构替换为对应字段的实际JS值类型:必填字段标注为对应原始类型,可选字段加?标识;嵌套数组要明确数组元素的实际存储结构。修正后的GameModel示例:
import { Document, model, Model, Schema } from "mongoose"; // 正确的文档类型:字段类型对应实际存储值,而非Schema配置 export type GameModel = Document & { image?: string, title: string, rank?: number, providerAmount?: number, nestedValues?: Array<{ RTP?: string, "Max Win"?: string, "Min Bet"?: string, Volatility?: string, Betways?: string, Release?: string, Devices?: string }> }
2. 给Schema关联自定义类型
原代码中new Schema()没有传入泛型参数,无法自动关联文档类型,会导致类型推导偏差,修正为:
// 给Schema指定文档关联类型,优化类型推导准确性 const GameSchema = new Schema<GameModel, Model<GameModel>>({ image: {type: String}, title: {type: String, unique: true, required: true, index: true}, rank: {type: Number}, providerAmount: {type: Number}, nestedValues: [ {RTP: {type: String}}, {"Max Win": {type: String}}, {"Min Bet": {type: String}}, {Volatility: {type: String}}, {Betways: {type: String}}, {Release: {type: String}}, {Devices: {type: String}} ] })
3. 调整查询方法的调用对象
不要直接在Schema实例上调用findOne,要使用model()返回的Model对象执行方法,修正后的业务逻辑:
const gameModel = model<GameModel>('Game', GameSchema) const game = await gameModel.create({ image: "test", title: "StarBurst" }) // 修正后,TypeScript会正确识别title参数允许传入字符串值 const queriedGame = await gameModel.findOne({title: "starburst"}) console.log(game)
调整完成后,TypeScript会正确识别findOne查询参数中title字段的可传入值类型,不再触发类型校验报错,数据创建、查询逻辑均可正常执行。
内容的提问来源于stack exchange,提问作者Kristoffer Tølbøll

