I have the following JSON:
{
"fields":[
{"name":"thom","techname":"rgom","description":"dfgkjd","type":"text"},
{"name":"thom","techname":"rgom2","description":"dfgkjd","type":"text"}
]
}
When I post it to a NodeJS-server using this code:
$.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");
}
}
});
And insert it:
db.collection('schemas').insert(fields, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
console.log(result);
}
});
In MongoDB I have:
"_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"
I was expecting:
{
"_id":ObjectId("5512ed12ecacf6e01da7aaa4"),
"fields":
[
{
"name":"thom",
"techname" : "rgom",
"description" : "dfgkjd",
"type" : "text"
},
{
"name":"thom",
"techname" : "rgom2",
"description" : "dfgkjd",
"type" : "text"
}
]
}
EDIT: Logged before insert:
[ { '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 } ]
EDIT 2 Console logged before insert (using JSON.stringify()):
{
"_id" : ObjectId("5512f0d4606391f41ddd16d1"),
"{"fields":[{"name":"sdkljg","techname":"fgklj","description":"dfgklj","
type":"text"}]}" : ""
}
The format that you got when you logged fields before the db insert indicates that you sent the data as form params from the client to the server. If doing that, you would have to manually convert it back into an object to insert into mongodb. It would be much easier if you instead just sent it as a json string so that you wouldn't have to transform it server-side.
data: JSON.stringify(data),
contentType: 'application/json'