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

235
Visualizações
Why does Mongoose insert null as the last element of the subdocuments array?

I have a Mongoose schema with an array of subdocuments, that looks like this:

const cardsSchema = new mongoose.Schema({
  cards: [
    {
      front: String,
      back: String,
      nameOfSuperset: String,
      nameOfSet: String,
    },
  ],
});

const Cards = mongoose.model("Cards", cardsSchema);

I have created a document from the above model, and I am pushing a couple of objects in the array of subdocuments of this document:

exports.createCards = async (req, res, next) => {

  const userCards = await Cards.findById(req.user.cards);

  for (let i = 0; i < req.body.cards.length; i++) {
    userCards.cards.push(req.body.cards[i]);
  }

  const created = await userCards.save();
  console.log(created);

  res.status(201).json({
    status: "success",
  });
};

When I console.log this saved document, or look at it in MongoDB Compass, there is null in the document at the end of the subdocuments array. I am not pushing any empty objects in this document. The original array, from which I get objects to push (req.body.cards) doesn't have null elements or empty objects. I have console.logged it.

What is this null and how can I get rid of it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

replace for loop with forEach

req.body.cards.forEach(item=>{
userCards.cards.push(item)
})
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