0

I work on a quiz application for my BD. I'm trying to update my MongoDB collection once the user correctly answers a question inside the Course collection (there will be multiple questions).

This is what I've tried so far - everyone seems to recommend this syntax, but it doesn't work for me. I am able to update everything outside the course object from the database.

mongodb database structure

router.put("/course", async (req, res) => {
  await Course.update(
    { _id: req.body.courseId, "course.questionId": req.body.questionId },
    {
      $addToSet: {
        "course.$.taken": [{ status: 1, attempts: 1, userId: req.body.userId }]
      }
    }
  );
});

Once again - I am trying to append a new object to the "taken" array with the userId, status of the question (failed/passed), and the number of attempts.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Alex
  • 125
  • 2
  • 9
  • Basically the first linked duplicate is using the same essential code approach you are. It works and it's the answer ( hold placed to stop people from just writing that exact same answer ). Why yours does not work is up to you to show more detail than what you presently have. You notably do not inspect the result of the `update()`, so it probably does not match anything due to being fed incorrect parameters. Also you are probably using "mongoose". If so then show the schema so we can see if `questionId` is properly defined as an `ObjectId` type. – Neil Lunn Mar 23 '19 at 23:41
  • If you are NOT using mongoose and just the base driver, then all values which are actually `ObjectId` need to be cast as such manually since any values in the `req.body` are just going to be "strings". And "duplicate 2" shows additional and alternate syntax which would not be necessary to "append" but is necessary for update. There is also information there on why you probably should avoid "nesting arrays" where possible. People always "nest" for "relational" reasons to *make things easy*. It actually makes things worse. It's a very common misconception. – Neil Lunn Mar 23 '19 at 23:44

0 Answers0