【问题标题】:nestjs mongoose Type 'string' is not assignable to type 'Condition<LeanDocument<User>>nestjs mongoose 类型 'string' 不可分配给类型 'Condition<LeanDocument<User>>
【发布时间】:2021-06-25 00:19:35
【问题描述】:

我正在使用带有猫鼬的nestjs。我尝试做一个简单的查找查询

 this.challengesModel.find({ createdBy: userId })

this.challengesModel 像这样被注入的地方

 private readonly challengesModel: Model<Challenge>

但它说

Type 'string' is not assignable to type 'Condition<LeanDocument<User>>'

createdBy 被认为是一个用户对象,而我给它一个 string(userId) 如何仅通过 id 搜索将 createdBy 字段保留为用户?

这是我的架构

@Schema()
export class Challenge extends Document {
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: "User" })
  createdBy: User;

  @Prop()
  description: string;

  @Prop({ default: new Date() })
  creationTime: Date;

  @Prop()
  video: string;

  @Prop({ default: [] })
  likes: string[];

  @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }] })
  selectedFriends: User[];

  @Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: "Reply" }] })
  replies: Reply[];
}

createdBy 保存为用户的唯一 id(用户集合的外键) 我正在尝试执行查询以查找由具有特定 ID 的用户创建的挑战。 如果我将 createdBy 更改为 string(id) 它可以工作,但是我没有获得所有用户属性,nest 文档也建议像我一样创建它。 为了能够在没有任何编译错误的情况下进行此查找,我应该进行哪些更改?

【问题讨论】:

  • 尝试类似:this.challengesModel.find({ createdBy: new ObjectId(userId)}) 可能会从字符串创建 objectId
  • 设法使其与 this.challengesModel.find({ createdBy: userId } as FilterQuery) 一起工作

标签: mongodb typescript mongoose nestjs


【解决方案1】:

试试

 this.challengesModel.find({ createdBy: userId as any })

这是因为 createdBy 不是字符串类型。

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2021-09-26
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多