2017-07-24 76 views
0

我需要使用jquery & ajax將多個對象插入到mongodb json數組中。我只想更新mealReviews數組。同時保持一切。但是當我使用PUT方法時,它會用新輸入的信息替換我現有的代碼。如何使用jQuery和jQuery添加多個對象到嵌套的json數組

{ 
"_id": { 
    "$oid": "57afc7636" 
}, 
"mealIDa": "ACT", 
"mealIDb": "TMNT2", 
"genre": "Action", 
"title": "Teenage Mutant Ninja Turtles 2 The Secret of the Ooze", 
"description": "The Teenage Mutant Ninja Turtles (Mark Caso, Michelan Sisti, Leif Tilden, Kenn Troum) again battle their archenemy, the rogue ninja Shredder (Francois Chau). Shredder attempts revenge by obtaining the same radioactive ooze that created the Turtles and unleashing two new monstrous mutants: Tokka, an oversized snapping turtle, and Rahzar, a fearsome wolf-like creature. When Shredder plans to use the remaining ooze on himself, the Turtles must harness their ninja fighting skills to stop him.", 
"poster": "TMNT2.jpg", 
"mealPoster": "tmnt2.jpg", 
"mealSrc": "02 Teenage Mutant Ninja Turtles II The Secret of the Ooze.mp4", 
"releaseDate": "March 22, 1991", 
"language": "English", 
"subtitle": false, 
"srt": "Teenage Mutant Ninja Turtles II The Secret of the Ooze.srt", 
"director": "Michael Pressman", 
"actors": "Paige Turco \"April O'Neil\", Vanilla Ice, Michelan Sisti \"Michelangelo, Soho Man\", Robbie Rist \"Michelangelo\", Kevin Clash \"Splinter\"", 
"studio": "Golden Harvest Company, New Line Cinema, Northshore Investments Ltd.", 
"hrs": 1, 
"mins": 28, 
"ratings": "PG \u2013 Parents Cautioned", 
"dateAdded": "2017-07-18T20:59:17.473Z", 
    "mealReviews": [ 
    { 
     "username": "user1", 
     "accountType": "viewer", 
     "subject": "Great movie!", 
     "rating": "4", 
     "review": "the best of the time", 
     "reviewDate": "2017-07-24T21:03:00.786Z" 
     } 
     ] 
    } 

    var mealReviews = []; 
    var mealData = ({ 
     "username": mealUsername, 
     "accountType": mealAccountType, 
     "subject": mealSubject, 
     "rating": mealRating, 
     "review": mealReview, 
     "reviewDate": reviewDate 
    }); 


    mealReviews.push(new Object(mealData)); 

然後我使用AJAX PUT方法更新mongodb,更新數組時是否正確?

 $.ajax({ url: 'https://api.mlab.com/api/1/databases/movie_meals/collections/meals/'+ meal_id + '?apiKey=JVUavJ75zT7u4s2_0Ihmzjn6sS9TEEpn', 
     data: JSON.stringify({ 
     "mealReviews": mealReviews 
     }), 
      type: "PUT", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success:function(data){ 
      $('#mealDetails').hide(); 
      $('#admin').hide(); 
      $('#meals').show(); 
      }, 
      error:function(xhr,status,err){ 
      console.log(err); 
      } 
     }); 

回答

0

您需要回發之前檢索的整個對象,並更改mealReviews屬性。

var meal = // do whatever magic to get your meal object from Mongo 
meal.mealReviews = mealReviews; 
// save your 'meal' object in the way you described 
+0

它的工作!非常感謝! –