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);
})};