HOW TO find, Edit and SAVE with mongoose

Tell us what’s happening:
I found the Person document with the search key, then edited its array of favoriteFoods, and saved with save. But it doesn’t work as expected… How to solve this??

Your code so far

var findEditThenSave = function(personId, done) {
  var foodToAdd = 'hamburger';
  
  const foundPerson = Person.findOne({_id:personId}, function(err, data){
    if(err) console.error(err);
    done(null, data);
  });
  
  foundPerson.favoriteFoods.push(foodToAdd);
  
  foundPerson.save();
  
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0.

Challenge: undefined

Link to the challenge:
https://www.freecodecamp.org/learn/apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save

  var foodToAdd = 'hamburger';
  
  const foundPerson = Person.findOne({_id:personId}, function(err, data){
    if(err) console.error(err);
    consolse.log('getting ready to call done');
    done(null, data);
  });
  console.log('getting ready to push data into favoriteFoods');
  foundPerson.favoriteFoods.push(foodToAdd);
  console.log('getting ready to call save');
  foundPerson.save();

Add the above console.log statements and see if the order makes sense to you.

1 Like