I am trying to save a 3D array in MongoDB, so obviously I decided to save the data as JSON. For simplicity, I am trying to save Weekly Food Menu, so the array dimensions are: Week x Day x ArrayOfMenuItems.
Restaurant.js (Model)
menuItems: {
type: 'json',
defaultsTo: null
}
Here is the result object I created and want to parse into JSON:
[ ,
[ ,
,
[ '538498de6a965778228e7e0e' ],
[ '538498ed6a965778228e7e0f' ],
[],
[],
[] ],
[ ,
,
[ '538498de6a965778228e7e0e', '538499156a965778228e7e11' ],
[],
[],
[],
[] ],
[ , , [], [], [], [], [] ],
[ , , [], [], [], [], [] ]
]
JSON.stringify(result):
[null,[null,null,["538498de6a965778228e7e0e"],["538498ed6a965778228e7e0f"],[],[],[]],[null,null,["538498de6a965778228e7e0e","538499156a965778228e7e11"],[],[]
,[],[]],[null,null,[],[],[],[],[]],[null,null,[],[],[],[],[]]]
Then I save it to database:
restaurant.menuItems = JSON.stringify(result);
restaurant.save(function(err) {
if (err) return res.serverError("Failed to save menu items");
});
In the next call, when I try to parse restaurant.menuItems I get "Uncaught Exception: Unexpected token ,"
console.log('BEGIN-{0}-END'.format(restaurant.menuItems)); // see print
var currentItems = JSON.parse(restaurant.menuItems); // throws exception
However, this is not surprising, because the print message before calling JSON.parse gives:
BEGIN-,,,538498de6a965778228e7e0e,538498ed6a965778228e7e0f,,,,,,538498de6a965778228e7e0e,538499156a965778228e7e11,,,,,,,,,,,,,,,,,,-END
What I am doing wrong here and how are attributes of type "json" should be used? I must be done something wrong, but there is no documentation or example on using it.
I believe I can find a workaround if I save the "Stringified JSON text" as string in database, but this would look ugly.
Any ideas?