Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
mongoose schema string type is not working

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
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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! :)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda