Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly.

Here is a snippet of my API code:

.post('/type/add', function(req, res){
   var type = new NewType({
      type: req.body.type,
      subtype: req.body.subtype,
   });
   type.save(function(err, newTypeOne){
      if(err){
         res.send(err);
         return;
      }
      res.json({message: "New type Created!"});
   });
})

This is the MongoDB schema I am using:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Type = new Schema({
    type: String,
    subtype: String
});
module.exports = mongoose.model('NewType', Type);

Below is my controller:

.controller('AddTypeController', ['CreateType', 'AllType', '$location', function(CreateType, AllType, $location){
   vm = this;
   vm.createType = function(){
     vm.message = '';
     CreateType.create(vm.typeData)
       .success(function(data){
       vm.typeData = '';
       
       vm.message = data.message;
       $location.path('/type')
       });
   };
   
   AllType.getAll().success(function(data){
      vm.types = data;
   });
}])

And here is the service I am using:

angular.module('typeService', [])
.factory('AllType', function($http){
   var typeFactory = {};
   typeFactory.getAll = function(){
      return $http.get('/api/type');
   };
   return typeFactory;

})
.factory('CreateType', function($http){
   var typeFactory = {};
   typeFactory.create = function(typeData){
      return $http.post('/api/type/add', typeData);
   };
   return typeFactory;
})

My HTML structure:

<div ng-controller="AddTypeController as type">
<form>
   <md-select ng-model="type.typeData.type" placeholder="Type">
      <md-option ng-value="typeone.type" ng-repeat="typeone in type.types">{{typeone.type}}</md-option>
   </md-select>
   <md-input-container flex>
      <label>SubType</label>
      <input ng-model="type.typeData.subtype">
   </md-input-container>
   <button ng-click="type.createType()">Send</button>
</form>
</div>

However, I am facing an issue:

For example, when I add a new record with TypeOne and SubTypeOne. The database reflects {type: TypeOne, subtype: SubTypeOne}. Next, when I try to add another subtype to TypeOne, the first select options duplicates TypeOne instead of listing all subtypes under it. What I want is to store subtypes as an array like: {type: TypeOne, subtype:[subtype: SubTypeOne, subtype: SubTypeTwo]}. But I am unsure how to achieve this.

Answer №1

When designing your model, remember to define subtypes as an array of strings to easily push new values onto it. Check out the example code snippet below:

var Type = new Schema({
    type: String,
    subtype: [String]
});

To update existing data in mongoose, consider using the findOneAndUpdate method instead of simply creating a new entry every time. Take a look at this example code snippet:

CreateType.findOneAndUpdate({type: 'type1'},
    {$push: {subtype: 'type2'} },
    function(err, data) {
    if (err)
        // Handle creation of a new entry here
    else
        // Return a 200 OK response or other appropriate action
});

This approach allows you to efficiently update arrays without duplicating entries. I recommend exploring the findOneAndUpdate documentation for more insight, along with the $push mongo documentation.

I hope this information proves helpful! I've recently been working on an application that follows these principles, and can confirm their effectiveness through practical experience.

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

The issue with populating after a find query in order to use the $near operator in Mongoose

My attempt to retrieve user information for their location is resulting in the value undefined being returned. Below are the schemas I am using: AnnounceSchema: const AnnounceSchema = new mongoose.Schema({ title: String, content: String, image: Str ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Failure to retrieve data with ajax call in php script

I am a beginner in the world of JS and PHP. I am taking on the challenge of teaching myself. Following the guidance provided in this answer from Stack Overflow, I attempted to implement it in my project. Unfortunately, I am facing challenges and would gre ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

Sending the most recent result to each dynamically created div

In my WordPress project, I have an event panel that displays upcoming event details and shows the remaining time until the next event. The countdown dynamically gets values from the database and calculates the time left based on the user's input in th ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Guidelines for choosing a single integer from a collection of integers and floating-point numbers that have been extracted from a string

In my code, I have a set of doubles and ints that I parsed named gradeList. This data will be passed to a constructor. The grade list looks like this: "5 - 90 85 95.5 77.5 88" The '5' is an integer but the rest should be double values. My parsing ...

Apache2 is displaying a 403 Forbidden Error

Working on setting up Apache2 on my Ubuntu system has been a successful endeavor. However, I am encountering a challenge in configuring a server for my AngularJS project's HTML pages. Currently, the directory is as follows: <Directory /var/www/htm ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

Show and Arrange Various Key-Object Data pairs

I'm facing a challenge with mapping and displaying a JSON file in a different structure. I need help figuring out how to map the data properly. Here's the JSON file: var data = { "megamenu": [ { "name": "level1.2", "link": "#", ...

Implementing class changes based on scroll events in JavaScript

const scrollList = document.getElementsByClassName('scrollList'); function scrollLeft() { scrollList.scrollLeft -= 50 } function scrollRight() { scrollList.scrollLeft += 50 } #scrollList { display: flex; overflow: auto; width: 10 ...

Exploring the Ins and Outs of Debugging JavaScript in Visual Studio Using

I encountered a peculiar issue while testing some code. When the program is executed without any breakpoints, it runs smoothly. However, if I introduce a breakpoint, it halts at a certain point in the JSON data and does not allow me to single-step through ...

"Composing perfect sentences: The art of incorporating quotes

I am attempting to include text with quotes in a DIV, like so: "All is well that ends well" The text is generated dynamically and I'm using a JavaScript font replacement plugin (CUFON) to add quotes around the text. Sometimes, the ending quote drops ...

Issue: It is not possible to display a <Router> within another <Router>. It is important to only have one router in your application

An error is occurring in my React application because I have nested routers. I need to use a second router in Navbar.js for the <Link> component to work. Currently, I have React Router implemented in two different files, and if I remove one of them, ...

Tips for resolving the error message: React is not able to identify the `currentSlide` and `slideCount` prop on a DOM element

I recently implemented an image slider using "react-slick" in my next.js project. However, I encountered some warnings in the console related to the 'currentSlide' and 'slideCount' props on a DOM element. Warning: React does not recogni ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

Is there a way to execute a condition in a Vue component before rendering the HTML in the template?

Here is an example of my Vue component: <template> <div id="modal-transaction" class="modal fade" tabindex="-1" role="dialog"> ... <div class="modal-header"> <h4 class="modal ...

Is it true that document.execCommand only works with buttons and not links?

Below is the code snippet I am working with: <div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div> <a class='bold' style="height:10px;width:10px;">B</a> $(function(){ ...