Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
CastError while making a put request for a user in Expressjs

I am making a post request on the API endpoint http://localhost:5000/api/notes/updatenote:id where id is an id of a particular user. The API just simply updates the notes associated with the user where notes is itself a MongoDB collection with their own id. I am trying to make the PUT request but I am getting this error. I had made a lot of commit for an easy understanding of the code, but in case of any doubt, you can ask me for more information.

Error

CastError: Cast to ObjectId failed for value ":61473ebd4ce15cca37954d28" (type string) at path "_id" for model "notes"

code for PUT

//ROUTE 3 :Update notes of a particular user PUT:/api/notes/updatenote:id

router.put("/updatenote:id", fetchUser, async (req, res) => {
  console.log("put request starts");

  const { updatedTitle, updatedDescription, updatedTag } = req.body;
  //console.log(req.body);

  //Create a newNote object
  let newNote = {};
  if (updatedTitle) {
    newNote.title = updatedTitle;
  }
  if (updatedDescription) {
    newNote.description = updatedDescription;
  }
  if (updatedTag) {
    newNote.tag = updatedTag;
  }

  console.log("param val - "+req.params.id)

  //finding the note to be updated and update it
  let noteToBeUpdated = await Notes.findById(req.params.id); //id in the parameter
  console.log(noteToBeUpdated);

  if (!noteToBeUpdated) {
    return res.status(404).send("Not found");
  }

  //req.user.id == person ki id who is updating and notetobeupdated.user = jiska note update ho rha uski id
  if (noteToBeUpdated.user.toString() !== req.user.id) {
    return res.status(401).send("Unauthorised User");
  }

  noteToBeUpdated = await Notes.findByIdAndUpdate(
    req.params.id,
    { $set: newNote },
    { new: true }
  );

  res.json({ noteToBeUpdated });

});

Request body

{
   "title":"First song (debut)",
   "description":"First Debut song in launched in 2015.",
   "tag":"music"
}

notes collection

[    {
    "_id": "61473ebd4ce15cca37954d28",
    "user": "61432ac5225cd230999f178d",
    "title": "First song",
    "description": "First song in English language worldwide.",
    "tag": "science",
    "date": "2021-09-19T13:44:29.386Z",
    "__v": 0
    }
]

Full log of Errorenter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

your string _id contains : and mongoose could convert this string to objected change router.put("/updatenote:id" to router.put("/updatenote/:id"

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda