0

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?

user2867106
  • 1,139
  • 1
  • 13
  • 31

1 Answers1

1

You are specifying the menuItems attribute as type json, but then setting the field to a string value (i.e. the stringified JSON). This is valid, because a string is valid JSON, but it's not what you want. Just set the attribute to the result object directly, without stringifying it first. Waterline handles the internal task of serializing / deserializing the data if necessary at the adapter layer (MongoDB and Postgres handle JSON natively, so no serializing is necessary).

sgress454
  • 24,870
  • 4
  • 74
  • 92