Search code examples
node.jsmongodbmongoosenestjsmongoose-schema

Cast to ObjectId failed for value "{ id: '5f1c64aa177bf9379491ecc8' }" at path "_id" for model "User"


I'am trying to make simple todoapp with Nestjs. I have two module one is User and Task. Task module works just fine i can add new task, findbyId method works fine.I can add new User but when i've tried to findbyId in user model this happen {"statusCode":500,"message":"Internal server error"} error.

user.schema.ts:

export const UserSchema = new mongoose.Schema({  
    email: {type:String},
    nickname:{type:String, required:[true, 'Nickname is required']},
    password:{type:String, required:[true, 'Password is required']},
    tasks: { type:Array },
    updateAt:{type:Date, default:Date.now},  
}) 

user.service.ts:

async getOne(id:string): Promise<User>{
    return await this.userModel.findById(id).exec();
    }

task.schema.ts

export const TaskSchema = new mongoose.Schema({
    title: { type:String, required:true},
    user: {type:String ,required:true},
    description: {type:String, required:false},
    category: {type:String,required:true},
    updateAt:{type:Date, default:Date.now}
})

task.service.ts

async getOne(id: string): Promise <Task>{
    return await this.taskModel.findById(id).exec();
}

Thank you for your time !


Solution

  • Seems like your id value in the getOne method is not actually a string, but rather an Object containing:

    { id: '5f1c64aa177bf9379491ecc8' }

    So you could change this to call findById with the actual id:

    async getOne(idHolder: any): Promise <Task>{
    
        return await this.taskModel.findById(idHolder.id).exec();
    }