0

I'm updating/saving an array to Mongodb using Monk and an Express app. The object I'm saving is something like

let entry = {"a": "string", "b":["stringa", "stringb"]}.  

After I save it, it appears in the db as

{"a": string, "b[]": ["stringa", "stringb"]} 

I checked the schema using MongoDB Compass and it has a string, b undefined, I have not set a schema. Data is from a multi-select drop down form field which creates the array. I'm using Ajax to save it to the db:

$.ajax({
          type: 'PUT',
          data: entry,
          url: dbUrl + dbCollection,
          dataType: 'JSON' }).done(function(res) {});

I am checking entry right before this (using chrome console log and it shows up correctly), after I save it, looking in the db, I get two items named b, b and b[] with b being "" and b[] containing the array.

Why does it add the brackets and what can I do to avoid it?

Edit: It turns out it is jquery adding the brackets, not mongo, see: $.ajax appending [ ] to the key issue with brackets in jQuery Form Data when sending data as json

with a workaround in the links.

  • Do share respective data schema. – Abhinav Kinagi Jul 27 '19 at 03:44
  • 1
    You need to show code that reproduces the problem. But I suspect that you are parsing form input ( as `application/x-www-form-urlencoded` ) which is resulting an a field in the object being interpreted as `"b[]"` instead of `"b"` because it's an *array with multiple values* in the form – Neil Lunn Jul 27 '19 at 09:57

0 Answers0