MongoDB and Mongoose - Perform Classic Updates by Running Find, Edit, then Save

const findEditThenSave = (personId, done) => {
  let foodToAdd = "hamburger";
  Person.findById(personId, (err, data) => {
    if (err) return console.log(err);
    data.favoriteFoods.push(foodToAdd);
    data.save((err, data) => {
      if (err) return console.log(err);
      done(null, data);
    });
  });
};

This is the Solution. It worked for me.
In myApp.js in glitch:

var findEditThenSave = function(personId, done) {
  var foodToAdd = 'hamburger';
  Person.findById(personId,(err,data)=>{
    if(err){
      done(err);
    }
    data.favoriteFoods.push(foodToAdd);
    data.save((err,data)=>{
      if(err){
        console.log(err);
      }
      done(null,data);
      console.log(data);
    });
    //done(null,data);
  });
  //done(null/*, data*/);
};

This is the link to my glitch: https://glitch.com/~ink-sunset-supply

2 Likes

Iā€™m working through this challenge now and your work was very helpful. Thanks for sharing.

Bro.That URL didā€™t work.

Youā€™re Welcome. It is Your reply that helped me.

Thank you. This thread helped a lot! From the Mongoose docs I could see I needed to add a function and two arguments to .save(), but I still didnā€™t understand that I needed to complete the findById callback first,

  1. findById finds the document, and then performs a callback function (and either returns an error or performs its callback function)
  2. That callback function, using the document passed from findById, then performs a save on that document
  3. The save operation itself performs a callback function (and either errors or returns that updated document)
<REDACTED>

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original posterā€™s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.