如何使用angular度追加表单字段以及如何在数据库中插入值

我使用express和mongoose来保存mongodb中的数据。 我正在创buildNode API,下面是我的Mongo Schema。

var bookSchema=new Schema({ subject_name:{type:String}, books:[{book_name:String, book_author:String}] }); 

我的HTML视图如下

在这里输入图像描述

我想在一个主题名称上添加多个书籍。 所以我想知道如何使用Angularjs多次添加Books部分,以及如何在mongodb中存储它的值。

我期望的结果是这样的:

在这里输入图像描述

请让我怎么做到这一点。

提前致谢。

嘿,你可以检查,如果这有助于SubjectBooks是mongoose模式。 通过subjectName将新书追加到主题中的查询。 如果要查找具有其他任何参数(如_id)的对象,则可以更改update方法的第一个参数。

节点代码在这里

EDITED

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; /*....mongoose connection creation code goes here...*/ var bookSchema=new Schema({subject_name:{type:String},books[{book_name:String, book_author:String}] }); var SubjectBooks = mongoose.model('<collection_name>', bookSchema); app.post('<URL mapping goes here>',function(req,res){ var subject = req.body; //You have to use body-parser var subjectName = subject.subject_name; var subjectModel = new SubjectBooks(subject); subjectModel.save(function (err,mongRes) { if(err){ res.send(err); } res.json(mongRes); }); }); 

我创build的angular度代码

 app.controller("mainController",["$scope",'mainService',function($scope,mainService){ $scope.subjectBookCatalogue = { subject_name: "", books:[{ book_name:"", book_author:"" }] }; $scope.saveSubjects = function (data) { mainService.saveSubjects(data).then(function(response){ console.log(response.data); },function(response){ }); }; $scope.subjects = []; $scope.fetchSubjects = function () { mainService.getAllSubjects().then(function(response){ console.log(response.data); $scope.subjects = response.data; },function(response){ }); }; $scope.fetchSubjects(); $scope.submitForm = function(){ console.log($scope.subjectBookCatalogue); $scope.saveSubjects($scope.subjectBookCatalogue); } }]); app.factory("mainService",["$http",function($http){ return { saveSubjects : function(data){ return $http({ method:"POST", url: "http://localhost:3000/v1/subject/"+data.subject_name, data:data, headers: { 'Content-Type': 'application/json' } }); }, getAllSubjects : function(){ return $http({ method:"GET", url:"http://localhost:3000/v1/subjects" }); } } }]); 

这应该有助于将书籍推入主题书籍数组中。

你可以参考这个问题

  • 在Mongo DB中保存和插入有什么区别?