Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

318
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda