MongoDB Challenge: Perform Classic Updates

Tell us what’s happening:
I am trying to finish the challenge MongoDB and Mongoose - Perform Classic Updates by Running Find, Edit, then Save, but after hours of searching and tinkering I cannot get it to work.

I am supposed to…

  1. find a person by _id
  2. Add “hamburger” to their liste of favorite foods using Array.push()
  3. use save() inside the find callback

While I am comfortable doing each of these in isolation, I have no idea how to combine them. I have tried using “this” to refer to the current Person, but this is out of desperation.

Your code so far

 var findEditThenSave = function(personId, done) {
  var foodToAdd = 'hamburger';
  Person.findById({_id: personId}, (err, data) => {
    this.favoriteFoods.push(foodToAdd);, data) {
      if (err) console.error(err);
      done(null, data);
    if (err) console.error(err);
    done(null, data);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36.

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

Link to the challenge:

Are you working on this locally or on a service like Glitch?

Sorry, it’s on Glitch. Here is the relevant preceding code:

const mongoose = require("mongoose");

const mongoURI = process.env.MONGO_URI;
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true });

const Schema = mongoose.Schema;

const personSchema = new Schema({
  name: { type: String, required: true },
  age: Number,
  favoriteFoods: [String]

const Person = mongoose.model("Person", personSchema);

const arrayOfPeople = [
  {name: "Sarah", age: 33, favoriteFoods: ["salmon", "ice-cream"]}, 
  {name: "Tim", age: 29, favoriteFoods: ["chocolate", "chocolate"]}, 
  {name: "Dwayne", age: 43, favoriteFoods: ["pain", "pizza"]}

const createManyPeople = function(arrayOfPeople, done) {
    Person.create(arrayOfPeople, function(err, people) {
      if (err) console.error(err);
      done(null, people);

Are you able to send a copy of the Glitch via a link? I’d like to play around with your code before trying to give you any answers.

Sure thing. Here you go!

To be more specific: I’m having trouble accessing result of searching by ID. I keep getting the error “TypeError: Cannot read property ‘favoriteFoods’ of undefined”. I have tried assigning it to a variable, like so:

const foodToAdd = 'hamburger';

const findEditThenSave = function(personId, done) {
    let toEdit = findPersonById(personId, done);
    toEdit.favoriteFoods.push(foodToAdd);, data) {
        if (err) return console.error(err);
        done(null, data)

and chaining the methods like this:

const foodToAdd = 'hamburger';

const findEditThenSave = function(personId, done) {
    findPersonById(personId, done).favoriteFoods.push(foodToAdd).save(function(err, data) {
        err ? done(err) : done(null, data);

…but to no avail.