Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda