Problem: When sending data to MongoDB via AJAX, the subarry name points[0][x] is becoming a single string: "points[0][x]". How do I prevent the key from becoming a single string?
I added an object into MongoDB using Ajax post like this:
if(errorCount === 0) {
var newDesign = {
filename: 'designs/documents-desktop.jpg',
title: 'Tester',
slug: 'tester',
pos: '1',
points: [
{
x: '0.40',
y: '0.211',
title: 'test',
content: 'Blank for now'
},
{
x: '0.295',
y: '0.090',
title: 'Another Test',
content: 'Blank for now again'
}
]
}
$.ajax({
type: "POST",
data: newDesign,
url: "/data/add-design",
dataType: 'JSON',
}).done(function(response) {
if(response.msg === '') {
} else {
alert("ERROR: " + response.msg);
}
});
}
Then I use getJSON to GET this, and use console.log to output this.points[0][x]:
$.getJSON('/data', function(data) {
$.each(data, function() {
console.log(this.points[0][x])
});
});
But it doesn't work and I get this error:
Uncaught TypeError: Cannot read property '0' of undefined
You can see that all of the data is there when your console.log the entire object, but each subarray key is a single string:
{"_id":"54bcb74584a4c8bd05e3d772","filename":"designs/documents-desktop.jpg","title":"Tester","slug":"tester","pos":"1","points[0][x]":"0.40","points[0][y]":"0.211","points[0][title]":"test","points[0][content]":"Blank for now","points[1][x]":"0.295","points[1][y]":"0.090","points[1][title]":"Another Test","points[1][content]":"Blank for now again"}
You can also see in a mongo terminal that points[0][x] is becoming a single string:
db.filelist.find().pretty();
{
"_id" : ObjectId("54bcc85384a4c8bd05e3d777"),
"filename" : "designs/documents-desktop.jpg",
"title" : "Tester",
"slug" : "tester",
"pos" : "1",
"points[0][x]" : "0.40",
"points[0][y]" : "0.211",
"points[0][title]" : "test",
"points[0][content]" : "Blank for now",
"points[1][x]" : "0.295",
"points[1][y]" : "0.090",
"points[1][title]" : "Another Test",
"points[1][content]" : "Blank for now again"
}
Is there something I'm missing here? I don't seemingly have any mistakes in the server side with NodeJS and Express. What could be the problem?