Exploring the power of MongoDB arrays in combination with AngularJS

How can I insert data into MongoDB using AngularJS's $http service when one of the variables is an array stored in the collection?

Variables: - nome: string. - autor: string. - genero: array. - info: string.

Collection: mangas.

db.mangas.insert({nome: 'toriko', autor:'test', genero:['Ação','Aventura'], info:'...'})

Server.Js, Find mangas.

app.get('/mangas', function(req, res){
  console.log('I receive a get request');
  db.mangas.find(function (err, mangas){
    console.log(mangas);
    res.json(mangas);
  });

});

Server.Js, Insert mangas.

app.post('/mangas', function (req, res) {
  console.log(req.body);
  db.mangas.insert(req.body, function(err, doc) {
    res.json(doc);
  });
});

index.html, ng-click="addManga"

<tr>
  <td><input class="form-control"manga.nome></td>
  <td><input class="form-control"manga.autor></td>
  <td><input class="form-control"manga.genero></td>
  <td><input class="form-control"manga.info></td>
  <td><button class="btn btn-primary" ng-click="addManga()">Add manga</button></td> ----adds the method found in the controller
</tr>

     <tr ng-repeat="manga in mangas">
       <td>{{manga.nome}}</td>
       <td>{{manga.autor}}</td>
       <td>{{manga.genero}}</td>
       <td>{{manga.info}}</td>
     </tr>

Controller.js

$http.get('/mangas').success(function(response) {
    console.log("I received the requested data");
    $scope.mangas = response;
  });

  $scope.addManga = function() {
    console.log($scope.mangas);
    $http.post('/mangas', $scope.mangas).success(function(response) {
      console.log(response);

    })};

Answer №1

When working with HTML, it is important to remember to use the ng-model attribute for binding with the controller.

For example:

<td><input class="form-control" ng-model="manga.nome"></td>

Instead of:

<td><input class="form-control" manga.nome></td>

In the controller:

Make sure to use $scope.manga instead of $scope.mangas since you are binding manga in the HTML input fields.

$scope.manga = {};
$scope.addManga = function() {
    console.log($scope.manga);
    $http.post('/mangas', $scope.manga).success(function(response) {
      console.log(response);

})};

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

Having issues with selecting the radio button and retrieving its value

I am attempting to retrieve data from my MongoDB Database and showcase it using React. In the database, there are 4 Attributes named Ques, Ques_type, Ans, and Options where Options is an array. My goal is to generate radio buttons for all the options while ...

Adding a geometry to three.js and dynamically rotating it in real-time

Check out https://jsfiddle.net/pmankar/svt0nhuv/ for more info. The primary large red icosahedron geometry continues rotating along the y-axis. I successfully incorporated a small red sphere geometry and merged it with the primary geometry. Everything was ...

Utilize React to reduce, replace, and encapsulate content within a span element

I have a Map that receives JSON data and generates a list item for each value. Then, I modify specific parts of the strings with state values. const content = { "content": [ { "text" : "#number# Tips to Get #goal#" ...

Create an array of subarrays in NSMutableArray where every pair of objects is grouped together, with a blank string included at

Question: I'm wondering if there is a more optimal approach to achieve this task or if the current method is already efficient enough? Requirements: Create a new array of objects containing unique pairs of strings from a given array, and finally add ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

Display interactive content according to radio button selection

I have 4 boxes, labeled a,b,c,d. When the user selects box a, specific content should be loaded: If image a is picked, load content 1 If image b is picked, load content 2 If image c is picked, load content 3 If image d is picked, load content 4 I want ...

How to efficiently display multiple array elements using a loop in PHP

I have stored an HTML table row in a variable called hostingItem: <?php ob_start(); ?> <tr> <td class="text-center"><?php echo $hosting; ?></td> <td class="text-cen ...

What is the reason behind having the activator of strict mode as the string 'use strict'?

While many users may associate strict mode with the code 'use strict'; or "use strict";, the question arises as to why strict mode is not activated with an expression like use strict; instead. ...

Clicking on anchor links does not cause the link to bubble up to the document, but right-clicking allows the

Below is the code snippet that I am currently working with - <ul id="sliderNav"> <li class="navTitle"><h3>Navy Mobile App</h3> <p class="navContent"><br>New Navy mobile application for accessing Navy information on ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

Injecting unpredictable values to individual numbers in a vertical list within a spreadsheet

I am trying to add unique random numbers to each element in a column of a table. I have attempted the following method, but it only adds the same random number to every element in that column. NewEdge(:,2) = NewEdge(:,2)+ randi(3); Is there a way to add ...

What is the method for comparing array elements to a regular expression in this particular scenario?

My array contains strings with a specific format: obj-meta_version-11_info obj-meta_version-12_info obj-meta_version-13_info I need to loop through this array to identify objects that adhere to this naming convention. I think the regex pattern should be ...

Passing Data to an AngularJS Directive

Hello fellow developers, I'm currently diving into the world of AngularJS and embarking on my journey of creating my very first directive. I've managed to make some progress but I've hit a roadblock when it comes to passing variables to my d ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to ach ...

Having difficulties testing the functionality of redux-form

I am struggling with testing react components that use redux-form. My integration tests are failing, indicating that I have not set up the tests correctly. There seems to be a consensus in discussions on this issue, both here and on GitHub. Any assistance ...

Top Python Web Framework with exceptional MongoDB integration

As I venture into developing a web app using data from my MongoDB collection, I find myself wanting to expand my Python skills beyond what I've been focusing on recently. It appears that most of the popular Python web development frameworks are geared ...

Unfortunately, CORS is preventing me from sending a POST request through AJAX

I'm currently working on integrating an API into my website. I'm attempting to send a POST request with JSON data, but I keep encountering an error code when trying to make the request. Interestingly, sending the request using curl does not pose ...

Designing a final splash screen for my game with the help of JavaScript, Cascading Style Sheets, and

I'm facing a challenge with setting up an end screen for my candy crush game. I have implemented a timer, but when the time runs out and certain conditions are met, the end screen fails to appear. Do you know what might be causing this issue? functio ...

How to retrieve the value from a JSON object when the key is unknown in JavaScript

Here is the JSON file I'm working with: { "status": 200, "msg": "OK", "result": { "files": { "count": 1, "pUnJbKzql0f2": { "name": "How ...