What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn't being stored. Here's a snippet of my code.

food.server.model.js

 var FoodSchema = new Schema({
 created: {
   type: Date,
   default: Date.now
 },
name: {
  type: String,
  default: '',
  required: 'Please fill Food name',
  trim: true
},
deal: [{
  dealtype: {
      type: String,
      default: '',
      trim: true
   },
 dealprice: {
    type: String,
    default: '',
    trim: true
  }
 }],
 user: {
  type: Schema.ObjectId,
  ref: 'User'
  }
});

foods.client.controller.js

// initial array setup

var deal = [ { dealtype: '',dealprice: '' }, {dealtype: '',dealprice: '' } ];

 $scope.food = {};
    $scope.food.deal = deal;
    $scope.addItem = function() {
        $scope.food.deal.push({
            dealtype: '',
            dealprice: ''
        });
    };

 // Create new Food
 $scope.create = function (isValid) {
   $scope.error = null;
    if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'foodForm');
    return false;
  }

  // Create new Food object
  var food = new Foods({
    name: this.name,
    deal:[{
            dealtype: this.dealtype,
            dealprice: this.dealprice,
          }],
  });

  // Redirect after save
  food.$save(function (response) {
    $location.path('foods/' + response._id);

    // Clear form fields
    $scope.name = '';
    $scope.dealtype = '';
    $scope.dealprice = '';
  }, function (errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};

create-food.client.view.html

<form name="foodForm" class="form-horizontal" ng-submit="create(foodForm.$valid)" novalidate>
  <fieldset>
    <div class="col-md-12">
        <md-input-container flex="">
        <label >Food Name</label>
        <input type="text" data-ng-model="name" id="name"  required>
    </md-input-container>
</div>
<div ng-repeat="de in food.deal">
   <div class="col-md-6">
       <md-input-container class="">
          <label class="" for="dealtype">Dealtype</label>
          <input type="text" data-ng-model="de.dealtype" id="dealtype"   >
       </md-input-container>
   </div>
   <div class="col-md-6">
      <md-input-container class="">
         <label class="" for="dealprice">Dealprice</label>
         <input type="text" data-ng-model="de.dealprice" id="dealprice"   >
      </md-input-container>
    </div>
</div>
<a href ng:click="addItem()" class="btn btn-small">add item</a>
<button  class="md-primary md-raised width-100 md-whiteframe-5dp" type="submit">Create  Food</button>

<div ng-show="error" class="text-danger">
    <strong ng-bind="error"></strong>
</div>
</fieldset>
</form>

Answer №1

To configure your schema without the nested array and to avoid any issues, try sending the data without a deal property. If this resolves the issue, consider structuring your schema with a subdocument.

If you are interested in setting up your deal property as a Subdocument, refer to the documentation provided here. You will need to define a separate schema for deal, similar to the example below:

var dealSchema = new Schema({
  dealtype: {
    type: String,
    default: '',
    trim: true
  },
  dealprice: {
    type: String,
    default: '',
    trim: true
  }
});

var FoodSchema = new Schema({
  ...,
  deal: [dealSchema]
})

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

Generating an in-page anchor using CKeditor 5

We are currently integrating CKEditor 5 into one of our projects. Our goal is to enable the end-user to generate an in-page anchor tag that can be accessed through other links (e.g., <a name='internalheading'> which can be navigated to via ...

Having trouble getting sweet alert to work with my PHP script

I’m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...

Selection dropdown not being populated by ng-options

After trying numerous examples to implement the changes, I am still facing issues. Even though I have an ng-model and clearly defined the object property I want to receive, it is not functioning as expected. Any assistance would be appreciated. Here is th ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Having issues with the onclick _dopostback function in MVC? It seems like the post

When attempting to execute a postback in ASP.NET MVC after confirming with JavaScript, the following button is used: <input type="submit" id ="RemoveStatus" value="Remove Status" name="button" onclick="return CheckRemove();"/> The JavaScript code f ...

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

What is the best way to access the following element of an array within a for..of loop with an if statement in Javascript?

Need help with creating a word filter that checks if index 1 is 'dog' and index 2 is 'cat' in an array. What should be checked in the next index for 'word'? let textContainer = ['bird', 'dog', 'cat& ...

Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code: var fs = require('fs'), path = require('path ...

Retrieving the value of a nested JSON object with a dynamic key

Currently, I am attempting to log a JSON key that is dynamic to the console. However, there is another nested object inside the main object that I also need to access a value from. The key of this nested object contains special characters, so I have been u ...

JavaScript code to retrieve and store data from API endpoints

I am working with a Web API endpoint that provides the location of a URL (). When a button is clicked, this API is called and a URL is returned. The file format could be PDF, Excel, or Word. I am looking for a way to download the file and save it to disk ...

Retrieve the nested value of an object using the specified key field

When using the DataGrid component from material-ui to display my data in a table, I encountered an issue with accessing nested values. Specifically, I have a nested array of data but am unable to retrieve the nested value within the datagrid using the key ...

Add an existing file or directory to your Intellij IDEA project

Recently, I've been experimenting with Intellij Idea 15.0.3 to develop a MEAN stack application. To kick things off, I followed the steps of File -> New -> Project -> Empty Project in order to create a blank project. Then, within Intellij Id ...

Eliminating divs and preserving content

Is there a way to remove certain DIV elements using jQuery or pure JavaScript without affecting the content within them? Here is an example structure: <div class="whatever_name"> <div class="whatever_name"> <h2>subtitle</h2&g ...

Implementing ng-submit in AngularJS to display results in a formatted table

The goal is to input some data that will update in {{urname}} and {{urcm}} within the table. However, the expression is not functioning as expected. Additionally, I am unable to open a new row in the table when submitting new comments. All the data appear ...

Is it possible to create a THREE.js form using a sequence of outlines?

Consider the scenario where three two-dimensional shapes are present. To keep things simple, let's envision them all as circles: Is there a method in THREE.js that allows for these shapes to be 'stacked' on top of each other vertically, res ...

What are the steps to resolve a peer dependency problem with npm?

I am facing a conflict in my package.json file with the following modules: react-router requires react 0.13.x redbox-react requires react@>=0.13.2 || ^0.14.0-rc1 After running npm install react, I ended up with version <a href="/cdn-cgi/l/emai ...

How can I activate ng-change using jQuery?

My select tag looks like this: <select ng-change="doSomething()" ng-model="myModel"> </select> Currently, I am using a jQueryUI control (combobox) for my select tag. However, the "change" event triggered from jQuery does not activate the ng-c ...

Selecting Laravel lists by month option

I'm encountering a problem here. The error message reads "Too few arguments to function App\Http\Controllers\ViewsController::OBviews(), 0 passed and exactly 1 expected" Here is my controller: public function OBviews($date) { ...

Guide for manually initiating the mouseleave event on a smartphone or tablet

Is there a way to change the color of a link to orange when it's hovered over? On mobile devices, the link should turn orange when touched and stay that way until the user clicks away. I'd like to manually trigger the mouseout event to remove th ...