Why can't I push values to the array?

Tell us what’s happening:
I’m doing the Perform Classic Updates by Running Find, Edit, then Save project under Back End Development and APIs - MongoDB and Mongoose section.
But I couldn’t push the new value foodToAdd to the favoriteFoods field because it’s undefined. It says “TypeError: Cannot read property ‘push’ of undefined”.
What’s going wrong with my code?? Thank you!

Your code

const personSchema = new mongoose.Schema({
    name: String,
    age: Number,
    favoriteFoods: [String]
});

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

const findLily = async () => {
    const lily = new Person({ name: "Lily", age: 5, favoriteFoods: ["Vanilla Cake", "Lollipop"] });
    await lily.save();
    const found = await Person.find({ name: "Lily" });
    console.log(found);
    console.log(found.favoriteFoods);    // undefined
    console.log(typeof (found.favoriteFoods));    // undefined
}

findLily();

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

Challenge: Perform Classic Updates by Running Find, Edit, then Save

Link to the challenge:

It’s been a while since I’ve done Mongoose.

I don’t see where you’re trying to push. And what does found log out as?

Hello @jadeyw7, I think your problem is that model.find() returns an array. Your code would work if you used model.findOne() which returns an object. Hope this helps.

Hi @kevinSmith! Sorry I didn’t put the push code there. The code should be:

const findLily = async () => {
    const lily = new Person({ name: "Lily", age: 5, favoriteFoods: ["Vanilla Cake", "Lollipop"] });
    await lily.save();
    const found = await Person.find({ name: "Lily" });
    console.log(found);
    console.log(found.favoriteFoods);    // undefined
    console.log(typeof (found.favoriteFoods));    // undefined
    found.favoriteFoods.push("hamburger");   // TypeError: Cannot read property ‘push’ of undefined
    await found.save();
}

findLily();

Also, the found returned in the terminal as:

[
  {
    _id: new ObjectId("622a42f4f8b0845116189886"),
    name: 'Lily',
    age: 5,
    favoriteFoods: [ 'Vanilla Cake', 'Lollipop' ],
    __v: 0
  }
]

But thanks to @Slimattcode - I changed Model.find() to Model.findOne() and it works perfectly!!

Thank you both for your help! :slight_smile:

Hi @Slimattcode! You are right!!! It works now! Thank you so much!! :smiley:

1 Like