Inserting documents into an array of objects in MongoDB

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.

Answer №1

Have you ever attempted this code snippet before?

        $addToSet:{
        "quizzes.$.usersAttempted":{
            _id:userId,
            correctAnswers: questionsCorrect,
            wrongAnswers: questionsWrong,
            answers
        }}});

It appears that by using this code, you are including the complete answer array...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PyMongo setup code experiencing a ServerTimeoutError when connecting to MongoDB Atlas

I'm attempting to run the initial code provided by MongoDB in order to connect to a cluster that I recently set up on MongoDB Atlas. Unfortunately, I am encountering a Server Selection Timeout Error. Despite my efforts, I have not been successful in ...

Converting a PHP array into easily readable text

Recently delving into PHP, I encountered a challenge with reading an array from a submitted form via $_POST. Here is the snippet of code I am working on: $email_text = array(var_export($_POST, true)); $body = ""; foreach ($email_text as $key => $value ...

When using the mapReduce() function in MongoDB, any undefined values within the scope will automatically be transformed into

If the "scope" parameter of mapReduce() is set to a variable with an undefined value, the map function will receive the variable with a null value instead of the undefined value. Is this understanding accurate? For instance, consider the following JavaScr ...

display or conceal a div when a radio button is selected

I need a way to display a specific div containing unique text once a radio button is selected, while hiding all other div sections. <?php foreach ($items as $item){ $i=1; echo ' <div class="form-check"> <input class="fo ...

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Can you explain the distinction in JavaScript between declaring a variable with `var a = xyz[]` versus `var a = xyz

Can someone clarify the difference between the following statements in JavaScript (or jQuery)? var a = xyz[] var a = xyz{} I tried looking it up online, but couldn't find a definitive answer. If anyone knows the difference, please enlighten me. ...

Restore to the prior iteration of jQuery

Encountered an issue after installing two libraries, one updating to jQuery 1.9.1 and the other installing 1.9.2. Found both versions of jQuery in my Scripts folder, so attempted an upgrade-package in nuGet to version 2.0.1. My project still requires com ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Arranging information based on key values

I have a data file containing numerical values in JSON format: { "automotive_auto buying and selling_1_2":2.66883E-06, "automotive_auto infotainment technologies_1_9_1":8.67917E-06, "automotive_auto insurance_1_3":1.41038E-06, "automotive_auto ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

In the event that the $state cannot be located, redirect to a different URL using Ui

Our platform is a unique combination of WordPress backend and AngularJS frontend, utilizing ui.router with html5 mode turned on and a base href="/" due to the stack sites being in the root of the site. We are currently facing an issue: 1) Previously, whe ...

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...

Parsing a multidimensional JSON array in Java: A step-by-step guide

I have a JSON array object with two dimensions as shown below {"enrollment_data":{"status":"Active","notes":"None","id":"983761"}} To extract the status, notes, and id from the above JSON array object, I have written the following code: JSONParser parse ...

Slick Slider - Defining the Initial Slide

My website features a dynamic carousel showcasing a basketball team's schedule, with games sorted by date for the current season. I am trying to align the slider to display the upcoming game at the center. How can I designate a specific slide as the ...

How can I import mongoose models into a single JavaScript file that is then included in a Node.js file?

As I develop a node app using mongoose with mongo, I have individual model files where I define all the data modules. I aim to consolidate all the data models into a single JavaScript file that can be included in the main node.js server file (server.js). L ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Tips on updating the arrow icon after clicking on a dropdown menu

HTML: <div class="customSelectContainer"> <ul> <li class="initial">Choose</li> <li data-value="value 1">Option 1</li> <li data-value="value 2">Option 2& ...

Discovering nearby locations with latitude and longitude in MongoDB with Mongoose

Schema: const location = new mongoose.Schema({ id:String, name:{type: String , required:true}, address:String, rating:{type:Number , "default":0, min:0 , max:5 }, facilities:[String], // geoJSON schema 1 coords: { ...