Home > Mobile >  mongoose schema string type is not working
mongoose schema string type is not working

Time:03-11

I used mongoose to create a schema that contains an array field called "favoriteFoods". But when I retrieved an instance and tried to push another food to this array, it failed and says "TypeError: Cannot read property 'push' of undefined". I looked up the type of this field, it showed "undefined" instead of "array". Why is it happening?

const personSchema = new mongoose.Schema({
name: {
    type: String,
    required: true
},
age: Number,
favoriteFoods: [String] //set up the type as an array of string
});

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

new Person({ name: "Lily", age: 5, favoriteFoods: "Vanilla Cake" }).save().catch(e => {
console.log(e);
})

Person.find({ name: "Lily" }, (err, data) => {
if (err) console.log(err);
console.log(data); // it gives me the object
console.log(data.favoriteFoods); // undefined
console.log(typeof (data.favoriteFoods)); // undefined
})

CodePudding user response:

It looks like you are saying favoriteFoods takes an array of strings, but you are passing it a string value NOT in an array. What's more, there is also no guarantee that your new Person is done being saved before you try to find it since the operation happens asynchronously

CodePudding user response:

The problem has been solved!

I made 2 changes -

  1. Passing an array to favoriteFoods instead of a single value (Thank you @pytth!!)
  2. Changing Model.find() to Model.findOne() because the 1st returned an array but the 2nd one returned an object

So the final code is:

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" });
    found.favoriteFoods.push("hamburger");
    await found.save();
}

Please correct me if I made any mistakes. Thanks! :)

  • Related