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

Create a JavaScript button that redirects to a different page within a React application

I am creating a div element using a for-loop and I want to link each div to the "/campaign" page with its respective id. When a div is clicked, I want it to navigate to the "/campaign/id" page and pass the id to the Campaign component. class Home extends ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

Storing JSON data in a MongoDb database using the Sails.js framework

I'm looking to build my database using an external API. To begin, I've created a function called loadData(req, res){} in my DBController that retrieves data from the API in JSON format. Now, I want to save this imported JSON data into my mongoDB ...

Ways to verify a correct email address using ReactJS

I'm currently working on a project using React.js and Next.js. I'm encountering an issue with handling the Axios response in Next.js as it's displaying "[object Object]" instead of the actual response data. How can I properly handle the resp ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

Click the navigation bar to toggle it on and off

I have a script that creates a navbar. Currently, the dropdown menu only opens when hovered over. The issue arises when accessing this on a mobile browser, as the dropdown menu does not open. How can I modify this script to make the dropdown menu open wh ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

Creating reactive behavior with a Promise initiated within a constructor - A guide

I am facing an issue with my Thing class. In the constructor, there is an asynchronous operation using fetch. Once the fetch completes, the result is assigned to a field in the Thing object: class Thing { constructor() { this.image = null ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Having difficulty coming back from a promise catch block

I'm struggling to populate a menu list from my PouchDB database because I am unable to retrieve anything within the promise that is executed after calling get on the db. Below is the code in question: <MenuList> {this.populateSavedClues()} ...

the intricacies of resizing a dijit dialog

My dialog is defined as shown below: <div data-dojo-type="dijit/Dialog" id="DetailDialog" class="dijitDialog" ... I have loaded a grid inside the dialog with 10 columns. var dialog = dijit.byId("DetailDialog"); dialog.set("content", this.Details); d ...

The Owl carousel animation fails to work in Chrome browser

I am currently customizing an HTML5 template that utilizes the Owl Carousel 1.3.2. My goal is to incorporate a smooth fade animation when transitioning between slider images. The code snippet below works perfectly in the Mozilla Browser, however, I'm ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...