mongoose insert document for each ajax call

Viewed 70

I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.

This my server:

app.post("/cp" , upload  , function(req , res){
            console.log('file uploaded succcessfully');
            var title = JSON.stringify(req.body.titles);
            var file = req.file;
 
            const courses = new Courses({ 
                // courseTitle:c_title,
                // courseSubtitle:c_subtitle,
                // courseAuthor : c_creator,
                // coursePrice : c_price,
                courseVideo :file ,
                courseTitles :title ,
                // courseSpecs : c_specs,
                courseValidation : 0
                });
                courses.save();
});

Mongoose insert a document with title and without file and a document with file and without title,

Ajax:

 if(e.submitter.id == "submitpostCp"){
          
         var data = {};
         data.titles = titlesLis;
         data.specs = specsLis;
         data.submit = "submitAll";
         var fileup =  new FormData($('#form')[0]);

      $.when(
         $.ajax({
            type: 'post',
            url: '/cp',
            data: JSON.stringify(data),
            contentType: 'application/json',
               xhrFields: {
               withCredentials: false
            },
            headers: {

            },
            success: function (data) {
               console.log('Success');
               console.log(data);

            },
            error: function () {
               console.log('We are sorry but our servers are having an issue right now');
            }

         })
         
       ).then(function() {
   
         $.ajax({
            url:'/cp',
            type: 'POST',
            contentType: false,
            processData: false,
            cache: false,
            data: fileup,
            success: function(res){
               //  alert(res);
 
            },
            error: function(){
                alert('Error: In sending the request!');
            }
        })    
       });
      }
1 Answers
Related