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.