Order in array is reversed when save in mongodb

276 views
Skip to first unread message

Alejandro Paciotti

unread,
May 3, 2014, 12:50:00 AM5/3/14
to nod...@googlegroups.com
Hi

I have a function that save a document in a mongodb database:

function savedata(name, data, next){

var ResultsModel=mongoose.model('Result',
{ name:String,
 create_at:{type:Date,default:Date.now},
 data:[]
});

var r=new ResultsModel();
r.name = name;
r.data = data;
r.save(function(err){
if(err) throw err;
next();
});
}


If i call a function with    savedata('reportname', ['field1': 100, 'field2': 200], function(err){ console.log('done') })

When i want retreive the data, the array is like this: ['field2': 200, 'field1': 100] . Perfectly reversed.

Any idea?




Jose Luis Rivas

unread,
May 3, 2014, 1:59:31 AM5/3/14
to nod...@googlegroups.com
An Array is ['field1', 100, 200].

Key-based is an Object.

If you save an object, with {'field1': 100, 'field200': 200 } it will be
saved lexicographically.

Kind regards.

On 5/2/14, 11:50 PM, Alejandro Paciotti wrote:
> Hi
>
> I have a function that save a document in a mongodb database:
>
> function *savedata*(name, data, next){
>
> var ResultsModel=mongoose.model('Result',
> { name:String,
> create_at:{type:Date,default:Date.now},
> *data:[]*
> });
>
> var r=new ResultsModel();
> r.name <http://r.name> = name;
> *r.data = data;*
> r.save(function(err){
> if(err) throw err;
> next();
> });
> }
>
>
> If i call a function with savedata('reportname', *['field1': 100,
> 'field2': 200]*, function(err){ console.log('done') })
>
> When i want retreive the data, the array is like this: *['field2': 200,
> 'field1': 100]* . Perfectly reversed.
>
> Any idea?
>
>
>
>
> Alejandro...@gmail.com <mailto:Alejandro...@gmail.com>
>
> --
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+un...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en
>
> ---
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to nodejs+un...@googlegroups.com
> <mailto:nodejs+un...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.

--
Jose Luis Rivas - http://joseluisrivas.net
Venezuela - GPG: 0xB9AC8C43

Alejandro Paciotti

unread,
May 3, 2014, 2:28:21 AM5/3/14
to nod...@googlegroups.com
I send to the function this:

[ { Periodo: '2010-08',
    Total: 1363371.31,
    CobradoSegunContrato: 700741.61,
    Cuota_Licitacion: 44565,
    Proyectado: 812304.29,
    Proximas_Adelantadas: 271622.7,
    Ultimas_Adelantadas: 161692 },
  { Periodo: '2010-09',
    Total: 973838.09,
    CobradoSegunContrato: 662753.06,
    Cuota_Licitacion: 16241.92,
    Proyectado: 514792.1,
    Proximas_Adelantadas: 60626.61,
    Ultimas_Adelantadas: 126851.5 }]

I save like this:

{
    "name" : "ingresos",
    "_id" : ObjectId("53648b1d1579089428dfb8ae"),
    "data" : [ 
        {
            "Ultimas_Adelantadas" : 161692,
            "Proximas_Adelantadas" : 271622.7,
            "Proyectado" : 812304.29,
            "Cuota_Licitacion" : 44565,
            "CobradoSegunContrato" : 700741.61,
            "Total" : 1363371.31,
            "Periodo" : "2010-08"
        }, 
        {
            "Ultimas_Adelantadas" : 126851.5,
            "Proximas_Adelantadas" : 60626.61,
            "Proyectado" : 514792.1,
            "Cuota_Licitacion" : 16241.92,
            "CobradoSegunContrato" : 662753.0600000001,
            "Total" : 973838.09,
            "Periodo" : "2010-09"
        }, 

etc.. etc..

I don't understand.

Thanks!

To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.

Angel Java Lopez

unread,
May 3, 2014, 5:22:15 AM5/3/14
to nod...@googlegroups.com
Ummm... but what is the problem?

You retrieved the array with the elements in the same order, that is, the array is the same. The only difference, is that EACH element is an object and the property order are mangled. But what is the problem for your program?

The initial email described another situation: mangled array. But apparently, this is not the case.

Angel "Java" Lopez
@ajlopez

Bruno Jouhier

unread,
May 3, 2014, 5:24:41 AM5/3/14
to nod...@googlegroups.com
You have 2 entries in your array and each entry is an object with 7 properties (Periodo, Total, etc.).

The entries are in the same order. This is what really matters.
The properties of the individual entries are in a different order. Why does it matter?

Note that V8 does not always enumerate properties in the order in which they have been inserted. This is generally true but not with numeric keys. See https://code.google.com/p/v8/issues/detail?id=164. This is not what you are observing here but this is something to be aware of.

Bruno

Alejandro Paciotti

unread,
May 3, 2014, 10:30:27 AM5/3/14
to nod...@googlegroups.com
The problem is that i use this object (data) for charts, where the order is very important.

In the initial email i wrote without copy & paste, and i think that was a problem with the configuration, but not. Apparently is a v8 behavior. 

I do not understand yet.

Thanks!

Angel Java Lopez

unread,
May 3, 2014, 10:35:43 AM5/3/14
to nod...@googlegroups.com
I still don't understand

The data object is in order, the first element is the original first element. And the second element is still the second element. Or not? According to your second email, the title of this thread "Order in array is reversed when save in mongodb" is NOT the case.

The array keeps the order.

In which way the order of PROPERTIES of EACH element has influence on the chart output?

Angel "Java" Lopez
@ajlopez

Alejandro Paciotti

unread,
May 3, 2014, 11:06:44 AM5/3/14
to nod...@googlegroups.com
Sory Angel, maybe I can not explain properly. 

The problem is with each elements in the data object  that are recorded in reverse order.

Imágenes integradas 1

I admit I conceptually confused with arrays and objects, but data is an array that contains objects of 7 elements. 

The problem is with the objects that are recorded invested. 

Periodo, Total, CobradoSegunContrato..... Ultimas_Adelantadas  becomes  Ultimas_Adelantadas, Proximas_Adelantadas, Proyectado... Periodo.

I hope I was more clear.

Thanks again.
 

Francesco Mari

unread,
May 3, 2014, 11:17:04 AM5/3/14
to nod...@googlegroups.com
You are clear, but I think that there is a misunderstanding problem.

The order of elements in an array is important. In fact, each element in the array is in the same order as you specified.

The order of properties in an object, on the other hand, is unspecified and can change from one JavaScript implementation to the other. When talking about objects and properties, the only important thing is that the same properties (associations between a name and a value) are retained, even if the relative order is changed.

This is what the others told you until now, I hope that another explanation from a different guy helps you refreshing your mind.

Alejandro Paciotti

unread,
May 3, 2014, 11:31:07 AM5/3/14
to nod...@googlegroups.com
Thanks Francesco!

I understood from your explanation what others guys wanted explain me.
 
So the question is: how can I keep the order of an object when is saved to mongodb? 

Note that I can not change as I get the information, it just comes to me (from another api, or other system, or another database)

Thanks!

Francesco Mari

unread,
May 3, 2014, 11:35:04 AM5/3/14
to nod...@googlegroups.com
You can't, is an implementation detail and there is no way to enforce the order of properties in JavaScript objects. Can you explain why is so important that the properties are represented in that order? What is not working properly if the order is not enforced?

Alejandro Paciotti

unread,
May 3, 2014, 11:56:37 AM5/3/14
to nod...@googlegroups.com
Yes!

I am developing an API that has to return a json in certain format to be displayed in a chart.

The API was already developed, but queries to databases delayed between 30 and 45 seconds. 

Then I thought about running the query once, save in mongodb, and then provide it from there. 

The report consists of a name, creation date, and a body of data. But I do not know how is the body, how many columns are, if they are nested. Only I have to record. 

When I send the body of the report from mongodb, reverses the order of the objects and the charts are not displayed correctly. 

As we have to solve, I temporarily created a table in another database engine, saved the report and now I serve from there. 

Meanwhile, I'm still learning. 

I am very grateful to the support of this group of users, really are exceptional!

Francesco Mari

unread,
May 3, 2014, 2:17:32 PM5/3/14
to nod...@googlegroups.com
I'm sorry to say this, but if the order of the column is important, then the data representation must be changed. Internally, in your MongoDB cache, you can represent your columns as an array of objects with "name" and "value" properties. This also means, though, that you have to implement your own logic to serialize to JSON, such that you provide to your consumers the JSON they expect.

This solution requires a lot of effort, and I don't reccommend adopting it. I give it here just as an idea, a bad one. The consumer of your data should instead be updated to consume information represented in a more meaningful way.

Ryan Schmidt

unread,
May 4, 2014, 6:25:17 PM5/4/14
to nod...@googlegroups.com
The order of objects in an array is not guaranteed in the JavaScript language, sorry.

If order is important to your application, then the data structure you need to use is an array, not an object.

Karl Tiedt

unread,
May 4, 2014, 8:05:55 PM5/4/14
to nod...@googlegroups.com


On May 4, 2014 6:24 PM, "Ryan Schmidt" <googl...@ryandesign.com> wrote:
>
> The order of objects in an array is not guaranteed in the JavaScript language, sorry.
>
> If order is important to your application, then the data structure you need to use is an array, not an object.
>

Sounds contradictory? I suspect you meant the order of properties in an object are not guaranteed?





>
> On May 3, 2014, at 09:35, Angel Java Lopez <ajlop...@gmail.com> wrote:
>
> > I still don't understand
> >
> > The data object is in order, the first element is the original first element. And the second element is still the second element. Or not? According to your second email, the title of this thread "Order in array is reversed when save in mongodb" is NOT the case.
> >
> > The array keeps the order.
> >
> > In which way the order of PROPERTIES of EACH element has influence on the chart output?
>

> --
> Job board: http://jobs.nodejs.org/
> Moderation policy: https://gist.github.com/othiym23/9886289#file-moderation-policy-md


> ---
> You received this message because you are subscribed to the Google Groups "nodejs" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.

> To post to this group, send email to nod...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/A3546BED-0CDD-4DD5-8668-1FF982243B47%40ryandesign.com.

Ryan Schmidt

unread,
May 5, 2014, 12:30:51 AM5/5/14
to nod...@googlegroups.com

On May 4, 2014, at 19:05, Karl Tiedt wrote:

> On May 4, 2014 6:24 PM, "Ryan Schmidt" wrote:
> >
> > The order of objects in an array is not guaranteed in the JavaScript language, sorry.
> >
> > If order is important to your application, then the data structure you need to use is an array, not an object.
> >
>
> Sounds contradictory? I suspect you meant the order of properties in an object are not guaranteed?

Indeed that’s what I meant; sorry for the confusion. The order of properties in an object are not guaranteed in JavaScript. When you enumerate over them, or use Object.keys(), they may come back in any order. If you need a particular order, use an array.

Alejandro Paciotti

unread,
May 5, 2014, 9:41:43 AM5/5/14
to nod...@googlegroups.com
Thanks Ryan: I understand.

All comments have been very useful to me.
--
Job board: http://jobs.nodejs.org/
Moderation policy: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.

Angel Java Lopez

unread,
May 5, 2014, 6:58:35 AM5/5/14
to nod...@googlegroups.com
I should have better info with a reference, but I guess that some methods in ecmascript 6 will have an order to retrieve properties. Maybe, there is already some specification in ecmascript 5.


--
Job board: http://jobs.nodejs.org/
Moderation policy: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages