0

I have a seeds.js file that contains data like this:

var newBus = new Bus({
  am: {
    route: [
      {
        coords: {lat: 35.645329, lng: -84.068154},
        address: "5408 Hutton Ridge Rd"
      }
  }
}

and when I call

newBus.save(function(err, data) {
    if (err) throw err;
    else console.log(data);
});

it stores it as something like this:

"am" : {
    "route" : [
        {
            "address" : "5408 Hutton Ridge Rd",
            "coords" : {
                "lng" : -84.068154,
                "lat" : 35.645329
            }
        }
    ]
}

I just noticed that it changed the order of lat, lng to lng, lat. I wouldn't think it would matter, but when I was doing an update to the seed data, the update only worked when I found the array that matched a specific lng, lat. It didn't work when I tried to find a match with lat, lng.

So why does MongoDB/Mongoose reorder the data?

Garrett Smith
  • 97
  • 2
  • 8

1 Answers1

0

This is not an array, it's an dictionary (object in javascript). This does not store any order. It's said in documentation.

You can read more about it here: http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf (section 4.3.3)

which says:

Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Morishiri
  • 874
  • 10
  • 23
  • Okay, that makes sense. But obviously MongoDB doesn't store it randomly, and lng, lat is not alphabetical order, so why does it end up ordered this way? – Garrett Smith Dec 03 '16 at 14:46
  • And I suppose the bigger question is should I depend on it being lng, lat if it will not always be ordered in that way? – Garrett Smith Dec 03 '16 at 14:50
  • I'm not expert in MongoDB topic, but you can check this question: http://stackoverflow.com/questions/18514188/how-can-you-specify-the-order-of-properties-in-a-javascript-object-for-a-mongodb It looks like the author is worried about the same thing as you are – Morishiri Dec 03 '16 at 14:53