2

I am using express and mongoose to save data in mongodb. I am creating Node API, Below is my Mongo Schema.

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

My html view is as below

enter image description here

I want to append books more than one in respect to a single subject name. So I want to know that How can I append Books section more than once using Angularjs and how to store its value in mongodb.

and I expect the result something like that:

enter image description here

Please Let me how can I do that.

Thanks in Advance.

Saurabh Sharma
  • 804
  • 6
  • 16
  • 42
  • may be this video will help you [link](https://www.youtube.com/playlist?list=PLZm85UZQLd2RyFN1IQWuOk8gBt0aJHE1F) – Akashii Mar 28 '17 at 08:28
  • Thanks for the video link @ThanhTùng I know how to insert data in db but I want to know that when I append boook section more than once then `ng-model` of appended elements will be more than once , so I need to create its array to submit it in db... so I want to know how I can insert appended data in DB – Saurabh Sharma Mar 28 '17 at 09:16
  • @SaurabhSharma you need help in nodejs code or angular code? Are you able to send the required data from UI to node backend server? – Samarth Mar 28 '17 at 09:28
  • Basically I need help in Nodejs.... I am able to insert data in DB when I have only one book.... If I have multiple books then I need help to insert data. – Saurabh Sharma Mar 28 '17 at 09:30
  • `book_name` and `book_author` html elements will append on click `Add More Books` button – Saurabh Sharma Mar 28 '17 at 09:32

1 Answers1

0

Hey can you check if this helps SubjectBooks is mongoose schema. The query for appending new books into the subject by subjectName. You can change first parameter of update method if you want to find objects with any other parameter like _id.

Node code goes here

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

Angular code that I have created

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

This should help for pushing books into a subject books array.

You can refer this question

Community
  • 1
  • 1
Samarth
  • 773
  • 1
  • 6
  • 14
  • hey, I don't want to update document. I want when I post newly fresh record in DB then do the same as `update` – Saurabh Sharma Mar 28 '17 at 10:40
  • What you need is `{upsert:true}` flag within update query. What this does is it insert new document if no document is found in the db. – Samarth Mar 28 '17 at 10:44
  • @SaurabhSharma I have updated my solution can you verify if this is what you need. Now it is inserting if new subject data comes in. – Samarth Mar 28 '17 at 10:46
  • One thing that I was missing was $each modifier due to which array of books was getting pushed into another object containing multiple books object. – Samarth Mar 28 '17 at 14:40
  • Hi, I go through your above given code and analyse that is for Update the existing document. But I don't have existing document. I am inserting and using `post` method. Or might be I am not getting which you trying to say. – Saurabh Sharma Mar 29 '17 at 05:41
  • From front end I am getting `{ "subject_name" : "Maths", "books" : [ { "book_name" : "Publications", "book_author" : "A.R Rehman" }, { "book_name" : "PS Publications", "book_author" : "Rohit Karla" } , { "book_name" : "PLA", "book_author" : "Mukesh Rathi" } ] }` So, Now I want to insert that JSON in a single request. – Saurabh Sharma Mar 29 '17 at 05:43
  • As per my need your logic is not working. I want to insert my data with below given schema `var SubSchema=new subjectSchema({ subject_name:req.body.subject_name, books:[ { book_name:req.body.book_name, book_author:req.body.book_author }, { book_name:req.body.book_name, book_author:req.body.book_author }, ... and so on. ] }); SubSchema.save(function(err,data){ if(err){res.json(err)} else{ res.json(data) } })` – Saurabh Sharma Mar 30 '17 at 07:57
  • Save will insert new document. why you are creating new schema every time just use operations on parent schema itself – Samarth Mar 30 '17 at 08:00
  • As in PHP , If we want to insert multiple value from same name attribute, so we make the `name="something[]"` like that and after serialize that generated array and then insert in to db. Same thing I want to do with Node.js...Please let me know if get some idea. – Saurabh Sharma Mar 30 '17 at 09:21
  • Hey @SaurabhSharma I have added mongoose model in the reply I guess what I am missing was `SubjectBooks` declaration. I have added those lines. Please check if now it helps – Samarth Mar 30 '17 at 17:39
  • Hi, I solved this issue what I need. By angular I am send data to api like ` $scope.dd={books:[{ "book_name":"", "book_author":"" }] }; $scope.addmore=function(){ $scope.dd.books.push({}); } $scope.cccc=function(){ $http.post('/multi', $scope.dd).success(function(res){ console.log(res); }) }` – Saurabh Sharma Mar 31 '17 at 05:33
  • and in Node API `router.post('/multi',function(req,res){ var SubSchema=new subjectSchema({ subject_name:req.body.subject_name, books:req.body.books }); SubSchema.save(function(err,data){ if(err){res.json(err)} else{ res.json(data) } }) })` Now I storing data as per my expectation and Schema Model – Saurabh Sharma Mar 31 '17 at 05:33
  • Ok great. But lets say I make another request with same subject name and add only one book in the request is it appending in mongo or just saving one entry after overriding all books array with just 1 entry even if earlier there were lets say 3 books for that subject? – Samarth Mar 31 '17 at 07:18
  • whatever you said its a condition of updation of existing document. But in my case I was not updating document instead I was inserting fresher document. Suppose I am saving a subject name and that subject contains more than one books, Thats why subject name was one but books name & author can be add more on demand. – Saurabh Sharma Mar 31 '17 at 11:14
  • That case can be handled just by using save command in my suggestion too. – Samarth Mar 31 '17 at 11:27