Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

319
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!