Search code examples
javascriptmongodbmongoosesubdocument

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?


Solution

  • replace for loop with forEach

    req.body.cards.forEach(item=>{
    userCards.cards.push(item)
    })