客户端生成的JSON存储在MongoDB服务器端,应用程序/JSON解析不正确?
我会很简短;我有一个可以创建“测验”的工具,这是一系列附有答案的问题,可以发送到服务器并存储到MongoDB。我已经试着按照我的想法去做,但是承诺的结果与我得到的结果不匹配 我希望JSON由嵌套对象组成,如下所示:客户端生成的JSON存储在MongoDB服务器端,应用程序/JSON解析不正确?,json,node.js,mongodb,Json,Node.js,Mongodb,我会很简短;我有一个可以创建“测验”的工具,这是一系列附有答案的问题,可以发送到服务器并存储到MongoDB。我已经试着按照我的想法去做,但是承诺的结果与我得到的结果不匹配 我希望JSON由嵌套对象组成,如下所示: { "_id": "54a884c68999af900fc28dcb", "name": "testquiz", "author": "user", "questions": [ { "text": "quest
{
"_id": "54a884c68999af900fc28dcb",
"name": "testquiz",
"author": "user",
"questions": [
{
"text": "question one",
"answers": [
{
"text": "answer one",
"correct": false
},
{
"text": "answer two",
"correct": true
}
]
},
{
"text": "question two",
"answers": [
{
"text": "answer one",
"correct": true
},
{
"text": "answer two",
"correct": false
}
]
}
]
}
但是,我只能得到如下结果:
{
"_id": "54a8b00108039068102f8835",
"quizname": "World War II",
"questions[0][text]": "When did WWII start?",
"questions[0][answers][0][text]": "1938",
"questions[0][answers][1][iscorrect]": "on",
"questions[0][answers][1][text]": "1939",
"questions[0][answers][2][text]": "1944",
"questions[0][answers][3][text]": "1914",
"questions[1][text]": "",
"questions[1][answers][0][text]": "",
"questions[1][answers][1][text]": "",
"author": "user"
}
我做错了什么?我是一个新手,非常感谢你的帮助。我明白了。我花了很多令人尴尬的时间,也花了很多令人心碎的搜索,但它确实奏效了
$('#savequiz').click(function () {
obj = {
quizname: $('#quizname').val(),
author: "",
questions: []
};
for (var i = 0; i < questionCount; i++) {
obj.questions.push({
text: $('#question_' + i).val(),
answers: []
});
for (var j = 0; j < answerCount[i]; j++) {
obj.questions[i].answers.push({
text: $('#question_' + i + '_answer_' + j + ' > div > input').val(),
correct: $('#question_' + i + '_answer_' + j + ' > div > span > input[type="checkbox"]').is(':checked')
});
}
}
$.ajax({
url: '/quiz/new',
type: "POST",
data: JSON.stringify(obj),
processData: false,
contentType: "application/json; charset=UTF-8"
});
return false;
});
app.post('/quiz/new', function (req, res, next) {
if (!req.session.loggedin) {
res.status(401).end();
return;
}
var quiz = req.body;
quiz.author = req.session.username;
db.collection('quiz', function (err, collection) {
collection.insert(quiz, {safe: true}, function (err, result) {
if (err) {
console.log('Failed to persist quiz!');
res.send({'error': 'An error has occurred'});
return;
}
console.log("Successfully persisted quiz.");
res.redirect('/');
});
});