Cannot PATCH (.findByIdAndUpdate is not a function)

Viewed 220

I'm trying to update a mongoDB database document for my To-Do list, I'm using Node, Mongoose, Express and Express Router.

Mongoose Schema:

const mongoose = require('mongoose');

const toDoSchema = new mongoose.Schema({

    value: {
        type: String,
    },
    category: {
        type: String,
    },
    _id: {
        type: String
    }
});

module.exports = mongoose.model('toDo', toDoSchema)

Patch code:

router.patch('/changeCategory', async (request, response) =>{
    
    const updateItem = new toDoModel({
        category: request.body.category
    })

    let id = request.body._id
    let category = request.body.category
    
    try{
        await updateItem.findByIdAndUpdate({_id: id},{category: category})
        response.json('Category changed')
    }
    catch (error){
        console.log(error.message)
    }
})

Insomnia request:

PATCH http://localhost:5000/changeCategory
{
    "category":"inProgress",
    "_id": "628de6210da8e45f52217083"
}

and what i get is "updateItem.findByIdAndUpdate is not a function"

1 Answers

This way is wrong. because you can't use findByIdAndUpdate with updateItem variable ..if you want use findByIdAndUpdate, you should use the imported model, then use this method.

example code:

const toDoModel = require("../models/your-model")

router.patch('/changeCategory', async (request, response) => {
  let category = request.body.category
  const updateItem = new toDoModel({
    category
  })

  let id = request.body._id

  try {
    // This part was changed *****

    await toDoModel.findByIdAndUpdate(id,{category: category})
    response.json('Category changed')

    // *******
  } catch (error) {
    console.log(error.message)
  }
})

I hope this solution helps you.

Related