'Unable to update using findByIdAndUpdate function inside router.put()

I am new to express and started with a todo app.

I am unable to update my todo list using findByIdAndUpdate() and even console.log in router.put() is not working. Don't know what is going wrong. I am confused. Please help..

My update function:

const express = require('express')
const mongoose = require('mongoose')
const task = mongoose.model('Task')

var router = express.Router();

router.put('/edit/:id', (req, res) => {

    console.log(req.params.id);

    const tname = req.body.taskName
    const tdesc = req.body.taskDesc

    task.findByIdAndUpdate(req.params.id, { taskName: tname, taskDesc: tdesc }, (err, doc) => {

        if (!err) {

            res.redirect('/task/list')
        }
        else {
            console.log('Error in updating ' + err)
        }
    })

})

This is my schema:

const mongoose = require('mongoose')

const taskSchema = new mongoose.Schema({

    taskName: {
        type: String
    },

    taskDesc: {
        type: String
    }

})

mongoose.model('Task', taskSchema);

In list.hbs file (displaying list as a table):

<div class="container">
    <div class="row">
    <div class="col-md-11 col-md-offset-11 col-centered">
        <h2 class="text-primary mt-5 text-center mb-3">List page</h2>
        <table class="table table-bordered">
            <thead class="thead-light">
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Task Name</th>
                    <th scope="col">Task Description</th>
                    <th scope="col"></th>
                </tr>
            </thead>
            <tbody>
                {{#each list}}
                <tr>
                    <th scope="row">{{this.list.id}}</th>
                    <td>{{this.taskName}}</td>
                    <td>{{this.taskDesc}}</td>
                    <td>
                        <a class="btn btn-success" href="/task/edit/{{this._id}}">Edit</a>
                        <a class="btn btn-success" href="/task/delete/{{this._id}}"> Delete</a>
                    </td>
                </tr>
                {{/each}}
               
            </tbody>
        </table><br>

        <a href="/task" type="submit" class="btn btn-primary"> Go Back</a>
        </div>
        
        </div>
</div> 

Package.json :

{
  "name": "todo-app",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.1",
    "bootstrap": "^4.6.1",
    "express": "^4.17.2",
    "express-handlebars": "^6.0.2",
    "mongoose": "^6.1.8"
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source