我有以下JSON:
{
"fields":[
{"name":"thom","techname":"rgom","description":"dfgkjd","type":"text"},
{"name":"thom","techname":"rgom2","description":"dfgkjd","type":"text"}
]
}
当我使用此代码将其发布到NodeJS服务器时:
$.ajax({
data : data,
type: 'POST',
dataType: 'json',
timeout: 10000,
url : '/schema/create',
success : function(response) {
console.log(response)
},
complete : function() {
},
error: function(x, t, m) {
if(t==="timeout") {
alert("Timeout");
} else {
alert("Der opstod følgende fejl:" + t + x + m + ". Kontakt COWI");
}
}
});
然后插入:
db.collection('schemas').insert(fields, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
console.log(result);
}
});
在MongoDB中我有:
"_id" : ObjectId("5512ed12ecacf6e01da7aaa4"),
"fields[0][name]" : "thom",
"fields[0][techname]" : "rgom",
"fields[0][description]" : "dfgkjd",
"fields[0][type]" : "text",
"fields[1][name]" : "thom",
"fields[1][techname]" : "rgom2",
"fields[1][description]" : "dfgkjd",
"fields[1][type]" : "text"
我在期待:
{
"_id":ObjectId("5512ed12ecacf6e01da7aaa4"),
"fields":
[
{
"name":"thom",
"techname" : "rgom",
"description" : "dfgkjd",
"type" : "text"
},
{
"name":"thom",
"techname" : "rgom2",
"description" : "dfgkjd",
"type" : "text"
}
]
}
修改 在插入之前记录:
[ { 'fields[0][name]': 'thom',
'fields[0][techname]': 'rgom',
'fields[0][description]': 'dfgkjd',
'fields[0][type]': 'text',
'fields[1][name]': 'thom',
'fields[1][techname]': 'rgom2',
'fields[1][description]': 'dfgkjd',
'fields[1][type]': 'text',
_id: 5512ed12ecacf6e01da7aaa4 } ]
编辑2 在插入之前记录控制台(使用JSON.stringify()):
{
"_id" : ObjectId("5512f0d4606391f41ddd16d1"),
"{"fields":[{"name":"sdkljg","techname":"fgklj","description":"dfgklj","
type":"text"}]}" : ""
}
答案 0 :(得分:3)
在db插入之前记录fields
时获得的格式表示您将数据作为params从客户端发送到服务器。如果这样做,您必须手动将其转换回要插入mongodb的对象。如果您只是将其作为json字符串发送,那么您就不必在服务器端进行转换。
data: JSON.stringify(data),
contentType: 'application/json'