4

Im about to make a huge schema for a form that I have just built... that being said does my schema order have to mimic the form order, or can it just have all the inputs in any order I put them in ? Example below. can it be like this?

// link to mongoose
var mongoose = require('mongoose');

// define the article schema
var mapSchema = new mongoose.Schema({
created: {
   type: Date,
   default: Date.now
},
dd1: {
    type: String,
    default: ''
},
dd2: {
    type: String,
    default: ''
},
com1: {
    type: String,
    default: ''
},
com2: {
    type: String,
    default: ''
}
});

// make it public
module.exports = mongoose.model('Map', mapSchema);

Or does it have to be like this?

// link to mongoose
var mongoose = require('mongoose');

// define the article schema
var mapSchema = new mongoose.Schema({
 created: {
   type: Date,
   default: Date.now
},
dd1: {
    type: String,
    default: ''
},
com1: {
    type: String,
    default: ''
},
 dd2: {
    type: String,
    default: ''
},
com2: {
    type: String,
    default: ''
}
});

// make it public
module.exports = mongoose.model('Map', mapSchema);

1 Answers1

5

does my schema order have to mimic the form order, or can it just have all the inputs in any order I put them in?

mongoose.Schema accepts a JavaScript object as its parameter. So your question boils down to:

Are JavaScript objects aware of the order their keys were defined in?

The answer to that is: No, key order is not maintained in JavaScript objects. The JS spec explicitly states that objects are unordered key/value collections. (compare)

Therefore it follows that mongoose.Schema could not rely on key order even if it tied to, which means you are free to order the keys in any way you like.


We can also tackle the question from the other end:

Is it likely that a front-end change like form field order forces me to rewrite my database backend code?

And the answer to that is: No, that is pretty darn unlikely. We can dismiss that thought without even looking into any kind of spec, because it would not make any kind of sense.

Community
  • 1
  • 1
Tomalak
  • 306,836
  • 62
  • 485
  • 598