由于存在唯一ID,{InsertMany猫鼬错误

时间:2020-03-06 14:04:05

标签: javascript node.js mongodb mongoose mongodb-query

我有以下代码段

    // Insert Question Archive into the DB (only at first execution needed)
      await QuestionArchive.insertMany(questionData.questionPool);
      // Get 20 random questions out of the existing Question Archive Collection and assign Room Number
      let selectedQuestions = await QuestionArchive.aggregate( [ { $sample: { size: 20 } } ]);
      selectedQuestions.forEach(question => {
        // At this point i should assure that selectedQuestions have NO _id so this gets newly generated
        question.room = req.body.room.title;
      });
      // Insert the random questions into the Question Collection
      Question.insertMany(selectedQuestions).then(inserted => {
        res.status(201).json({
          message: 'New Room created!',
          result: newRoom
        });
      }).catch(error => {
        console.error('Post CreateRoom - Question insertion error: ' + error);

实际上,在程序的第一次运行时,一个问题数组(QuestionPool)被加载到我的QuestionArchive集合中。然后,我从QuestionArchive中提取20个随机问题,并将其分别保存到问题集中!现在开始尝试,一切正常!第二次运行此代码后,我收到一个错误消息,因为从第一次运行开始,问题集合中已经有20个插入的随机问题中的一些。我实际上要做的是,在从QuestionArchive ==> Question中插入一个Question时,总是分配一个不同的“ _id”!那就是为什么不应该识别双数据集的原因!如何才能做到这一点?

非常感谢您的帮助!

0 个答案:

没有答案