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

241
Vistas
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 Respuestas
Responde la pregunta

0

replace for loop with forEach

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