0

Code snippetDoc tried editing enter image description here

User is the basic schema I created with a name, email, and password. But when I try to update it no errors occur yet the collection in mongodb doesn't change. Tried the {strict: false} option on the schema but sadly that just adds another object to it, debbuging mode didn't help much either so now I am stuck with no clues how to go about solving this. Any advice as to what might be happening? mongoose version is 6.0.12 and mongodb is 4.4.10 if they are of relevance.

// Snippet for the code.
User.findOneAndUpdate({_id: req.body.id}, {updatedUser}, {useFindAndModify: false}, (err) => {
   if(!err){
    console.log("Managed to update")
     res.json({message: "User updated successfully"})
   } else {
    res.json({message: `Something went wrong please try again => ${err} `})
   }
 }) 

3 Answers3

0

Add doc to callback function to see if you are getting updated document and this way you get better error messages.

// Snippet for the code.
User.findOneAndUpdate({_id: req.body.id}, {updatedUser}, {useFindAndModify: false}, (err, doc) => {
   if(!err){
    console.log("Managed to update")
    console.log(doc)
     res.json({message: "User updated successfully"})
   } else {
    res.json({message: `Something went wrong please try again => ${err} `})
   }
 })
Erenn
  • 625
  • 6
  • 18
  • Sadly i had to go to my college class and can't check if this works but I will give you an update asap when I get home. –  Nov 18 '21 at 09:44
  • As mentioned to @Joe returns the matching user but nothing seems to be updating. –  Nov 18 '21 at 19:16
0

_id is usually and ObjectId, req.body.id is usually string, so they don't match.

findOneAndUpdate is successful if no matching document is found.

Joe
  • 25,000
  • 3
  • 22
  • 44
  • It returns the user object with the matching _id tag but still doesn't update it. (Add photo in my latest eddit) –  Nov 18 '21 at 19:15
  • Check out https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document – Joe Nov 19 '21 at 10:21
0

I misread the documentation page and the whole problem was passing the { updatedUser } needed to be passed without the {}