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

315
Vistas
Mongoose - Modle.update() updates wrong document - Cast Error

I need some help to clear some things up.

I have a Model:

var Event = new Schema({
   event_code: String
 , segments: [Segment]
});

The creation of new documents work very well like perfect. When it comes to update certain documents I ran into some troubles.

When I do this (code below): = it only updates the first document, even if the id does not match

function edit_event (id, new_name, callback) {
  Event.update(id, {$set:{event_code: new_name}}, function(err, doc) {
    if (err) throw err;
    callback();
  });
}

When I do this (code below): = it gives me an Error (see below)

function edit_event (id, new_name, callback) {
  Event.findByIdAndUpdate(id, {$set:{event_code: new_name}}, function(err, doc) {
    if (err) throw err;
    callback();
  });
}

Error when using findByIdAndUpdate: Cast to ObjectId failed for value ""58fdbde31bff83141b376508"" at path "_id" for model "Event"

Please, i'm desperate :! :/

UPDATE

I figured out that the id that i'm trying to pass get stored with "" around it, so when i am looking for document with matching ID it puts an extra pair of "" around it so it ends up like ""id""

UPDATE 2

When I am listing all my documents, it returns:

{ _id: 58fdbde31bff83141b376508,

event_code: 'TestABC',

__v: 0,

segments: [] }

Then when i store the id in an HTML form it adds extra pair of "" around it ... that's not the case with event_code. Why is that ?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Looks like you performed unneeded JSON.stringify and that's why you get quotes around the id. Calling JSON.parse should solve the issue:

Event.findByIdAndUpdate(JSON.parse(id), {$set:{event_code: new_name}}, ...

about 4 years ago · Santiago Trujillo 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