title: Cast to ObjectId failed for value "undefined" at path "_listId" for model "Task"
body: <p>My Application is working if I use a link such http://localhost:4200/lists/5fcaab9a37b7a09f7c8ea32b, however, when I try to access http://localhost:4200/lists the connection of the server breaks with the error below. Any thoughts?</p>
  <blockquote>
  <p>CastError: Cast to ObjectId failed for value &quot;undefined&quot; at path &quot;_listId&quot; for model &quot;Task&quot;
  at model.Query.exec (C:\Users\camil\node_modules\mongoose\lib\query.js:4358:21)
  at model.Query.Query.then (C:\Users\camil\node_modules\mongoose\lib\query.js:4450:15)
  at C:\Users\camil\taskManager\api\app.js:95:8
  at Layer.handle [as handle_request] (C:\Users\camil\taskManager\api\node_modules\express\lib\router\layer.js:95:5)
  at next (C:\Users\camil\taskManager\api\node_modules\express\lib\router\route.js:137:13)
  at Route.dispatch (C:\Users\camil\taskManager\api\node_modules\express\lib\router\route.js:112:3)
  at Layer.handle [as handle_request] (C:\Users\camil\taskManager\api\node_modules\express\lib\router\layer.js:95:5)
  at C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:281:22
  at param (C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:354:14)
  at param (C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:365:14)
  at Function.process_params (C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:410:3)
  at next (C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:275:10)
  at C:\Users\camil\taskManager\api\app.js:24:5
  at Layer.handle [as handle_request] (C:\Users\camil\taskManager\api\node_modules\express\lib\router\layer.js:95:5)
  at trim_prefix (C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:317:13)
  at C:\Users\camil\taskManager\api\node_modules\express\lib\router\index.js:284:7 {
  messageFormat: undefined,
  stringValue: '&quot;undefined&quot;',
  kind: 'ObjectId',
  value: 'undefined',
  path: '_listId',
  reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
  at new ObjectID (C:\Users\camil\node_modules\bson\lib\bson\objectid.js:59:11)
  at castObjectId (C:\Users\camil\node_modules\mongoose\lib\cast\objectid.js:25:12)
  at ObjectId.cast (C:\Users\camil\node_modules\mongoose\lib\schema\objectid.js:267:12)
  at ObjectId.SchemaType.applySetters (C:\Users\camil\node_modules\mongoose\lib\schematype.js:1075:12)
  at ObjectId.SchemaType._castForQuery (C:\Users\camil\node_modules\mongoose\lib\schematype.js:1510:15)
  at ObjectId.SchemaType.castForQuery (C:\Users\camil\node_modules\mongoose\lib\schematype.js:1500:15)
  at ObjectId.SchemaType.castForQueryWrapper (C:\Users\camil\node_modules\mongoose\lib\schematype.js:1477:20)
  at cast (C:\Users\camil\node_modules\mongoose\lib\cast.js:331:32)
  at model.Query.Query.cast (C:\Users\camil\node_modules\mongoose\lib\query.js:4759:12)
  at model.Query.Query._castConditions (C:\Users\camil\node_modules\mongoose\lib\query.js:1841:10)
  at model.Query. (C:\Users\camil\node_modules\mongoose\lib\query.js:1868:8)
  at model.Query._wrappedThunk [as _find] (C:\Users\camil\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
  at C:\Users\camil\node_modules\kareem\index.js:369:33
  at processTicksAndRejections (node:internal/process/task_queues:75:11)
  }</p>
  </blockquote>
  <p>app.js</p>
  <pre><code>      const express = require('express');
  const app = express();
  const { mongoose } = require('./db/mongoose');
  // Load in the mongoose models
  const { List, Task } = require('./db/models');
  const bodyParser = require('body-parser');
  
  
  /* MIDDLEWARE  */
  // Load middleware
  app.use(bodyParser.json());
  
  //CORS HEADERS MIDDLEWARE
  app.use(function (req, res, next) {
      res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);
      res.header(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE&quot;);
      res.header(&quot;Access-Control-Allow-Headers&quot;, &quot;Origin, X-Requested-With, Content-Type, Accept, x-access-token, x-refresh-token, _id&quot;);
  
      res.header(
          'Access-Control-Expose-Headers',
          'x-access-token, x-refresh-token'
      );
  
      next();
  });
  
  /**
   * GET /lists
   * Purpose: Get all lists
   */
  app.get('/lists', (req, res) =&gt;{
      List.find({}).then((lists) =&gt; {
          res.send(lists);        
      });
  })
  
  /**
   * POST /lists
   * Purpose: Create a list
   */
  app.post('/lists', (req, res) =&gt; {
      // We want to create a new list and return the new list document back to the user (which includes the id)
      // The list information (fields) will be passed in via the JSON request body
      let title = req.body.title;
  
      let newList = new List({
          title,
          
      });
      newList.save().then((listDoc) =&gt; {
          // the full list document is returned (incl. id)
          res.send(listDoc);
      })
  });
  
  /**
   * PATCH /lists/:id
   * Purpose: Update a specified list
   */
  app.patch('/lists/:id', (req, res) =&gt; {
      // We want to update the specified list (list document with id in the URL) with the new values specified in the JSON body of the request
      List.findOneAndUpdate({ _id: req.params.id}, {
          $set: req.body
      }).then(() =&gt; {
          res.send({message: 'Updated Succesfully'});
      });
  });
  
  /**
   * DELETE /lists/:id
   * Purpose: Delete a list
   */
  app.delete('/lists/:id', (req, res) =&gt; {
      // We want to delete the specified list (document with id in the URL)
      List.findOneAndRemove({
          _id: req.params.id
      }).then((removedListDoc) =&gt; {
          res.send(removedListDoc);
  
          // delete all the tasks that are in the deleted list
          //deleteTasksFromList(removedListDoc._id);
      })
  });
  
  
  /**
   * GET /lists/:listId/tasks
   * Purpose: Get all tasks in a specific list
   */
  app.get('/lists/:listId/tasks', (req, res) =&gt; {
      // We want to return all tasks that belong to a specific list (specified by listId)
      Task.find({
          _listId: req.params.listId
      }).then((tasks) =&gt; {
          res.send(tasks);
      })
  });
  
  /**
   * GET /lists/:listId/tasks/:taskID
   * Purpose: Get all tasks in a specific list
   */
  app.get('/lists/:listId/tasks/:taskId', (req, res) =&gt; {
      // We want to return all tasks that belong to a specific list (specified by listId)
      Task.findOne({
          _id: req.params.taskId,
          _listId: req.params.listId
      }).then((task) =&gt; {
          res.send(task);
      })
  });
  
  
  /**
   * POST /lists/:listId/tasks
   * Purpose: Create a new task in a specific list
   * http://localhost:3000/lists/5fc3f7b5e4e0ce9394085d4d/tasks
   */
  app.post('/lists/:listId/tasks', (req, res) =&gt; {
      // We want to create a new task in a list specified by listId
  
            let newTask = new Task({
                  title: req.body.title,
                  _listId: req.params.listId
  
              });
              newTask.save().then((newTaskDoc) =&gt; {
                  res.send(newTaskDoc);
              })
      })
  
  /**
   * PATCH /lists/:listId/tasks/:taskId
   * Purpose: Update an existing task
   * http://localhost:3000/lists/5fc3f7b5e4e0ce9394085d4d/tasks/5fc3f877acc303780820db3c
   */
  app.patch('/lists/:listId/tasks/:taskId', (req, res) =&gt; {
      // We want to update an existing task (specified by taskId)
  
              Task.findOneAndUpdate({
                  _id: req.params.taskId,
                  _listId: req.params.listId
              }, {
                      $set: req.body
                  }
              ).then(() =&gt; {
                  res.send({message: 'Updated Succesfully'});
              })
  });
  
  /**
   * DELETE /lists/:listId/tasks/:taskId
   * Purpose: Delete a task
   * http://localhost:3000/lists/5fc3f7b5e4e0ce9394085d4d/tasks/5fc3f877acc303780820db3c
   */
  app.delete('/lists/:listId/tasks/:taskId', (req, res) =&gt; {
  
       Task.findOneAndRemove({
                  _id: req.params.taskId,
                  _listId: req.params.listId
              }).then((removedTaskDoc) =&gt; {
                  res.send(removedTaskDoc);
              })
          });
  
  
  
  app.listen(3000, () =&gt; {
      console.log(&quot;Server is listening on port 3000&quot;);    
  })
  </code></pre>
  <p>list.model.js</p>
  <pre><code>const mongoose = require('mongoose');
  
  const ListSchema = new mongoose.Schema({
      title: {
          type: String,
          required: true,
          minlength: 1,
          trim: true
      }
  })
  
  const List = mongoose.model('List', ListSchema);
  
  module.exports = { List }
  </code></pre>
  <p>app-routing.modules.ts</p>
  <pre><code>import { NgModule } from '@angular/core';
  import { CommonModule } from '@angular/common';
  import { BrowserModule } from '@angular/platform-browser';
  import { Routes, RouterModule } from '@angular/router';
  import { NewListComponent } from './pages/new-list/new-list.component';
  import { TaskViewComponent } from './pages/task-view/task-view.component';
  import { NewTaskComponent } from './pages/new-task/new-task.component';
  import { EditListComponent } from './pages/edit-list/edit-list.component';
  import { EditTaskComponent } from './pages/edit-task/edit-task.component';
  
  const routes: Routes = [
    { path: '', redirectTo: '/lists', pathMatch: 'full'},
    {path: 'new-list', component: NewListComponent},
    {path: 'edit-list/:listId', component: EditListComponent},
    {path: 'lists', component: TaskViewComponent },
    {path: 'lists/:listId', component: TaskViewComponent },
    {path: 'lists/:listId/new-task', component: NewTaskComponent },
    {path: 'lists/:listId/edit-task/:taskId', component: EditTaskComponent }
  ];
  
  @NgModule({
    imports: [RouterModule.forRoot(routes),BrowserModule,CommonModule],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }
  </code></pre>
  <p>task.service.ts</p>
  <pre><code>import { Injectable } from '@angular/core';
  import { WebRequestService } from './web-request.service';
  import { Task } from './models/task.model';
  
  @Injectable({
    providedIn: 'root'
  })
  export class TaskService {
    
  
    constructor(private webReqService: WebRequestService) { }
  
  
    getLists() {
      return this.webReqService.get('lists');
    }
  
   (...)
  }
  </code></pre>
  <p>web-request-service.ts</p>
  <pre><code>    import { Injectable } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
      
      @Injectable({
        providedIn: 'root'
      })
      export class WebRequestService {
      
        readonly ROOT_URL;
      
        constructor(private http: HttpClient) {
          this.ROOT_URL = 'http://localhost:3000';
        }
      
        get(uri: string) {
          return this.http.get(`${this.ROOT_URL}/${uri}`);
        }
      
        post(uri: string, payload: Object) {
          return this.http.post(`${this.ROOT_URL}/${uri}`, payload);
        }
      
        patch(uri: string, payload: Object) {
          return this.http.patch(`${this.ROOT_URL}/${uri}`, payload);
        }
      
        delete(uri: string) {
          return this.http.delete(`${this.ROOT_URL}/${uri}`);
        }
      }
  
  task-view.component.html
  
      &lt;div class=&quot;sidebar has-background-white&quot;&gt;
        &lt;h1 class=&quot;title has-text-primary&quot;&gt;
          Lists
        &lt;/h1&gt;
  
        &lt;div class=&quot;list-menu&quot;&gt;
          &lt;a class=&quot;list-menu-item&quot; *ngFor=&quot;let list of lists&quot; [routerLink]=&quot;['/lists', list._id]&quot; routerLinkActive=&quot;is-active&quot;&gt;
            &lt;p&gt; {{list.title}}&lt;/p&gt;
          &lt;/a&gt;
        &lt;/div&gt;
  
  
        &lt;button class=&quot;button is-primary has-text-white&quot; routerLink=&quot;/new-list&quot;&gt;+ New List&lt;/button&gt;
  
      &lt;/div&gt;
  </code></pre>