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

Viewed 2032

Im using nestjs with mongoose. I try to do a simple find query

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

where this.challengesModel is injected like this

 private readonly challengesModel: Model<Challenge>

but it says

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

createdBy is considered as a User object whereas I am giving it a string(userId) How can I still keep the createdBy field as User by search only by the id?

This is my schema

@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[];
}

The createdBy is saved as a unique id of the user (foreign key to the users collection) I am trying to perform a query to find challenges that were created by a user with specific id. If I change createdBy to be a string(id) it works, but then I don't get all the user properties, also the nest documentation suggests to create it like I did. What should I change in order to be able to do this find without any compliation errors?

1 Answers

Try

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

This is caused because createdBy isn't a string type.

Related