Typescript migration error

Hello comunity. I am learning typescript recently and Im rewriting my old JS project to typescript. Right now working with famous Todo application. Everything goes well, but im getting a weird error:

Todo validation failed: user: Cast to ObjectId failed for value “Model { User }” (type function) at path “user” because of “BSONTypeError”

It happens when I run app and login or register user and thentry to add some tasks.:
Tested all endpoints in app, and only this one causes this error message. Rest works well.
So it looks at error occurs during execution a fuction responsible for creating tasks , but cant find a path to the user, correct me if Im wrong.

this is the function from controller file

export const createTodo = async (
  req: Request,
  res: Response,
  next: (err?: Error) => any
) => {
  const { title, description } = req.body;
  try {
    const todo = await Todo.create({
      title,
      description,
      completed: false,
      user: User
    });
    res.status(201).json({ message: 'Task created successfully!', todo });
  } catch (error: any) {
    console.error(error.message);
    res.status(500).send({ error: 'Internal server error' });
  }```

and here is my user model:

```import mongoose, {Model, Schema} from 'mongoose';
import {TodoDocument} from './Todo';

type UserType = UserDocument & mongoose.Document;

export interface UserDocument extends mongoose.Document {
    params: any;
    _doc: any;
    name: string;
    email: string;
    password: string;
    age: number;  
}
export const schema: Schema<UserDocument> = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        email: {
            type: String,
            required: true,
            unique: true,
        },
        password: {
            type: String,
            required: true,
        },
        age: {
            type: Number,
            required: true,
        },
    },
    {timestamps: true}
);
export const User: Model<UserType> = mongoose.model<UserDocument>('User', schema);

And there is a link to whole repository if someone is willing to check it out.

1 Like