I am facing challenges while attempting to insert multiple objects into an array of objects in my development. The issue arises when trying to add more than one object with the same structure but different content.
This is the structure of the groups collection in my data model:
const userSchema = mongoose.Schema({
name: {type: String, required: true},
password: {type: String, required: true},
description: {type: String, required: true},
scope: String,
groupTeacher: {
type: mongoose.Types.ObjectId,
ref: 'users',
},
quizzes:[
{
_id: mongoose.Types.ObjectId,
name: String,
tier: Number,
category: String,
questions:[
{
_id: mongoose.Types.ObjectId,
title: String,
question: String,
correctAnswer: String,
answer1: String,
answer2: String,
answer3: String,
answer4: String
}
],
usersAttempted:[
{
_id: {
type: mongoose.Types.ObjectId,
ref: 'users',
},
correctAnswers: Number,
wrongAnswers: Number,
answers: [{
questionTitle: String,
correctAnswer: String,
usersAnswer: String
}]
I am specifically looking to add elements to the 'usersAttempted' array of objects. However, the challenge lies in inserting multiple sets of answers for each user attempt.
My current approach looks like this:
const result = await groupsModel.updateOne({
"_id": groupId,
"quizzes._id": quizId,
"quizzes.usersAttempted._id": {$ne: userId}
},
{
$addToSet:{
"quizzes.$.usersAttempted":{
_id: userId,
correctAnswers: questionsCorrect,
wrongAnswers: questionsWrong,
answers:{
questionTitle: answers[0].questionTitle,
correctAnswer: answers[0].correctAnswer,
usersAnswer: answers[0].usersAnswer
}
}}});
The 'answers' field is essential here as it represents an array of objects containing detailed responses to questions.
https://i.sstatic.net/iZxMD.png
Thank you for your support in resolving this issue.
EDIT: #1
To provide clarification:
I am aiming to append multiple arrays of objects to the 'usersAttempted' section, but my attempts have been unsuccessful in adding more than one set of responses.
EDIT: #2
I have successfully added an array of objects to the collection using indexes, but now I seek a solution for handling multiple objects without specific indexes.
const result = await groupsModel.updateOne({
"_id": groupId,
"quizzes._id": quizId,
"quizzes.usersAttempted._id": {$ne: userId}
},
{
$addToSet:{
"quizzes.$.usersAttempted":{
_id: userId,
correctAnswers: questionsCorrect,
wrongAnswers: questionsWrong,
answers:[{
questionTitle: answers[0].questionTitle,
correctAnswer: answers[0].correctAnswer,
usersAnswer: answers[0].usersAnswer
},
{
questionTitle: answers[1].questionTitle,
correctAnswer: answers[1].correctAnswer,
usersAnswer: answers[1].usersAnswer
},
{
questionTitle: answers[2].questionTitle,
correctAnswer: answers[2].correctAnswer,
usersAnswer: answers[2].usersAnswer
}]
}}});
I am now looking for a solution to add an array with a variable number of objects.