Utilizing ng-model in AngularJS to add data to an array in Mongoose and MongoDB

I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] to quiz.quizData.answers but it did not properly enter the data as an array. Instead, it was entered like this:

"answers" : [ 
            {
                "0" : "My First Answer",
                "1" : "My Second Answer"
            }
],

as opposed to how it should appear:

"answers" : [ 
    "My First Answer", 
    "My Second Answer"
],

Here is my HTML input form:

<input type="text" name="answers" ng-model="quiz.quizData.answers" placeholder="enter answers here" required>
<input type="text" name="answers2" ng-model="quiz.quizData.answers" placeholder="enter other answers here" required>

Endpoint:

// POST request for users to add a new quiz entry
    apiRouter.route('/quiz')

    .post(function(req, res) {
        // Create quiz object and assign it to 'quiz'
        var quiz = new Quiz();
        // Includes the quiz question
        quiz.question = req.body.question;
        // Contains an array with four quiz answers
        quiz.answers = req.body.answers;
        // Contains one string that represents the correct answer from the above array
        quiz.correctAnswer = req.body.correctAnswer;
        // Identifies the user creating the quiz
        quiz.postedBy = req.body.postedBy;
        // Specifies the quiz category
        quiz.category = req.body.category;
        // save the new quiz to the database
        quiz.save(function(err) {
            // If an error occurs, display error message in JSON format
            if (err) {
                return res.json({ success: false, message: 'something went terribly wrong....' + err });
            } else {
                // If no errors occur and it saves successfully, display success message
                res.json({ message: 'Quiz Created!' });
            }
        });
    });

MongoDB Schema:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

// post schema 
var QuizSchema   = new Schema({
    question: { type: String, lowercase: true, required: true },
    answers: { type: Array, required: true },
    correctAnswer: { type: String, required: true },
    category: { type: String, lowercase: true, required: true },
    postedBy: { type: String, required: true }
});

module.exports = mongoose.model('Quiz', QuizSchema);

Answer №1

If you are working with an empty array, simply utilize the ng-repeat directive to iterate a range:

<input ng-repeat="i in [1,2,3,4]" type="text" name="answers{{i}}" ng-model="quiz.quizData.answers[i]" placeholder="enter answers here" required>

For arrays of variable length, use ng-repeat with $index. Remember to include track by $index to avoid issues with duplicate keys:

<input ng-repeat="answer in quiz.quizData.answers track by $index" type="text" name="answers{{$index}}" ng-model="quiz.quizData.answers[$index]" placeholder="enter answers here" required>

Link to example on Plunker

Answer №2

Creating Form Fields in HTML

<input type="text" name="answer1" ng-model="answersArray[0]" placeholder="Answer 1">
<input type="text" name="answer2" ng-model="answersArray[1]" placeholder="Answer 2">
<input type="text" name="answer3" ng-model="answersArray[2]" placeholder="Answer 3">
<input type="text" name="answer4" ng-model="answersArray[3]" placeholder="Answer 4">
<input type="hidden" name="answers" ng-model="quiz.quizData.answers" placeholder="Enter answers here" ng-init="quiz.quizData.answers = answersArray">

Defining Array in Controller

$scope.answersArray = [
answer1 = $scope.answer1,
answer2 = $scope.answer2,
answer3 = $scope.answer3,
answer4 = $scope.answer4
];

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

Side-menu elevates slider

Struggling to keep my slider fixed when the side-menu slides in from the left? I've scoured for solutions without luck. Any expert out there willing to lend a hand? Code Snippet: https://jsfiddle.net/nekgunru/2/ ...

What could be the reason behind the index not getting properly set for the array that was cloned afterward?

I need assistance with a code snippet that clones an array, resets the index (0, 1, 2 ...), and stores it in a variable named buildingsPayload: console.log('1:', this.buildings) const buildingsPayload = this.buildings.map((building, index) => ...

How to Aggregate MongoDB Data and Group by a Single Field While Displaying All Fields

I am currently running version 6.2.9 of Mongoose and 4.4.13 of MongoDB In my schema called user_relationships, I have the following fields: _id - Object Id parent_user - Object Id child_user - Object Id relationship - String Essentially, I would like to ...

Organizing data in a database the arrangement way

I'm looking to populate an array with values for "name" and "nickname" extracted from an SQLITE database and then display them in an alert box. This task is part of a JavaScript project developed using Titanium Appcelerator. Below is the code snippe ...

Encountered a problem while attempting to establish a connection between Node JS and

I am encountering an issue while attempting to connect to Atlas MongoDB using Node.js. The error message TypeError: Cannot read property 'db' of null keeps popping up even though I have properly set up the cluster on Atlas, assigned full rights t ...

Generating new objects from API request in React and aggregating them into a single, comprehensive object

I have developed a program that utilizes Axios to fetch data through API calls. I aim to save the fetched result as an object within my this.state.matrixDictionary variable. However, each time I make another API call, the previous object gets replaced. My ...

Testing Angular 16 Component with Jasmine Spy and callFake Strategy

I've encountered an issue while trying to test my component unit. The problem arises when I call the product-list.component.ts from my product.service.ts. While my product.service.spec.ts is successful, the product-list.component.spec.ts fails as the ...

Jest: A guide on mocking esModule methods

In my code, I have a function that utilizes the library jszip to zip folders and files: // app.ts const runJszip = async (): Promise<void> => { const zip = new Jszip(); zip.folder('folder')?.file('file.txt', 'just som ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

Change occurring within a cell of a table that has a width of 1 pixel

In the code snippet below, there is a transition inside a table cell with a width of 1px to allow it to wrap its content. However, the table layout changes only at the end or beginning of the transition: var animator = document.getElementById("animator" ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Issues with validating the Google Maps API JavaScript tag

Currently working on updating a website to be fully validated with HTML5 using W3C standards. Having trouble validating the Google Maps API JavaScript tag in the code snippet below: <script src="http://maps.googleapis.com/maps/api/js?libraries=places& ...

Showing the outcome of the request from the backend on an HTML page using the MEAN stack

I am currently in the process of developing an angular application with a node.js + express backend. After successfully retrieving the necessary data from MongoDB and being able to view it through terminal, I encountered a challenge when trying to display ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Using jQuery to implement interactive hover effects on individual items within a list

I'm currently developing a project that involves displaying speech bubbles next to each list item when hovered over. These speech bubbles contain relevant information specific to the item being hovered on. To achieve this functionality, I've crea ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

Is there a way to select a checkbox in Google Forms using the console?

I need help with a script I'm creating to automatically populate Google Forms. I am able to select checkboxes using querySelector, but they don't have a .click() method or similar. How can I go about checking the checkboxes? ...

Submitting an ajax form with the use of the symbol '&'

I am currently working on a form submission using the .ajax() method. Within my script, I have the following code: data: dataString, The variable dataString is composed of: var list = $('.listsummary').val() The listsummary class is assoc ...