freeCodeCamp Challenge Guide: MongoDB and Mongoose - Perform Classic Updates by Running Find, Edit, then Save

Hints

Hint 1

Try to use .findOne() method to find person by id.

Hint 2

Use Array.push() method inside callback function to add given string to favoriteFoods array .

Hint 3

Don’t forget the save updated person with a callback function

Solutions

Solution 1
const findEditThenSave = (personId, done) => {
  const foodToAdd = 'hamburger';

  // .findOne() method to find a person by _id with the parameter personId as search key. 
  Person.findOne(personId, (err, person) => {
    if(err) return console.log(err); 
  
    // Array.push() method to add "hamburger" to the list of the person's favoriteFoods
    person.favoriteFoods.push(foodToAdd);

    // and inside the find callback - save() the updated Person.
    person.save((err, updatedPerson) => {
      if(err) return console.log(err);
      done(null, updatedPerson)
    })
  })
};

can you give some context?

do you need help? is this a suggestion for the guide?

yes its suggestion for the guide. and thats my first topic

thank you for your willingness to help

when you make a suggestion for the guide please include a link to the related challenge and/or guide article, and hide your code using the [details] tags

please also include a brief explanation of your code, and if possible some hints to arrive at the solution

thanks a lot for information. i edited

Thank you, for your guide post contribution. I have taken your suggestions and included them in the following guide post:

I did change your suggestion of findOne to findById, as the Mongoosejs docs recommend to always use findById, when using an id as the query.

We look forward to your further contribution.

1 Like