I'm trying to add elements into an array of objects, but I', having problems with adding more than 1 object.
This is the Model of my groups collection
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',
},
//userEmail: String,
correctAnswers: Number,
wrongAnswers: Number,
answers: [{
questionTitle: String,
correctAnswer: String,
usersAnswer: String
}]
I want to add elements into the 'usersAttempted' array of objects. I have problems with the 'answers' part. The problem is that there are many questions answers but, I only got it working for adding 1 questions answers.
This is how I did it.
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
}
}}});
Answers is an array of objects
Thank you for all your help.
EDIT: #1
Small explanation:
I have an array of objects, that I want to add to "usersAttempted" but I have problems with adding more than 1 answer.
EDIT: #2
I managed to add array of objects into the collection, but it is done with 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
}]
}}});
Now I want to find a way of adding an array with x number of objects.
