我需要使用jquery& amp;将多个对象插入到mongodb json数组中。阿贾克斯。我只想更新mealReviews数组。同时保持其他一切。但是当我使用PUT方法时,它用新输入的信息替换我现有的代码。
{
"_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 :(得分: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