为什么 Mongoose 插入 null 作为子文档数组的最后一个元素?

Why does Mongoose insert null as the last element of the subdocuments array?

我有一个包含子文档数组的 Mongoose 架构,如下所示:

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

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

我已经从上面的模型创建了一个文档,并且我在这个文档的子文档数组中推送了几个对象:

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",
  });
};

当我console.log这个保存的文档,或者在MongoDBCompass里看的时候,子文档末尾的文档里有null大批。我不会在本文档中推送任何空对象。我从中获取要推送的对象 (req.body.cards) 的原始数组没有空元素或空对象。我已经 console.log 搞定了。

这个 null 是什么,我怎样才能摆脱它?

forEach

替换for循环
req.body.cards.forEach(item=>{
userCards.cards.push(item)
})