Mongoose: fields reorder during save

Created on 5 Oct 2015  路  2Comments  路  Source: Automattic/mongoose

Hi,
i have below json object to insert in mongodb via mongoose orm which reorder fields when passed through schema initialization
Json object passed

{ _id: '56127440836751241a000003',
  Rolename: 'a',
  Modulename:
   [ 'redlime',
     'Modulename2',
     'module3',
     'Modulename',
     'mOdule123',
     'Modulename1',
     'awesome',
     'Modulename1' ],
  Accestype: [ 'View', 'create', 'allaccess' ],
  isactive: 'a' }

but when pass through schema initialization it becomes

e.g :-var mrole = new Mrole(req.body);

output which i am getting is below

{ Rolename: 'a',
  isactive: 'a',
  _id: 56127440836751241a000003,
  Accestype: [ 'View', 'create', 'allaccess' ],
  Modulename:
   [ 'redlime',
     'Modulename2',
     'module3',
     'Modulename',
     'mOdule123',
     'Modulename1',
     'awesome',
     'Modulename1' ] }
backwards-breaking

Most helpful comment

Unfortunately this is a limitation of how mongoose defaults work, as well as the key ordering problem of #2749. Mongoose defaults happen before document initialization, so Accestype and Modulename get their default value of [] set before the document gets initialized, which messes with the key order. Unfortunately changing this might be backwards breaking, because changing key orders can make people's queries miss indexes, which is bad. Gonna have to hold off on changing this until 5.0.

All 2 comments

Unfortunately this is a limitation of how mongoose defaults work, as well as the key ordering problem of #2749. Mongoose defaults happen before document initialization, so Accestype and Modulename get their default value of [] set before the document gets initialized, which messes with the key order. Unfortunately changing this might be backwards breaking, because changing key orders can make people's queries miss indexes, which is bad. Gonna have to hold off on changing this until 5.0.

Closing this in favor of #2749, which will be released with 5.0. Please follow that issue for updates :+1: :palm_tree:

Was this page helpful?
0 / 5 - 0 ratings