Mongoose: MongoDB generated ObjectID for arrays is descending instead of ascending

Created on 16 Jan 2020  路  3Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?

  • Report a bug or make sure it's designed like this

What is the current behavior?

I have the following document in a collection in my MongoDB database:

"_id":"5e2088563824e72ea5ee7095",
"image":"xxx",
"questions":[ 
    {
       "_id":"5e2088563824e72ea5ee70c3",
       "text":"test test test",
    },
    {
       "_id":"5e2088563824e72ea5ee70be",
       "text":"what is your age 1?",
    },
    {
       "_id":"5e2088563824e72ea5ee70b9",
       "text":"what is your gender 1?",
    },
    {
       "_id":"5e2088563824e72ea5ee70b4",
       "text":"what is your blood type 1?",
    },
    {
       "_id":"5e2088563824e72ea5ee70af",
       "text":"what is your blood type 1?",
    }
],
"__v":0

Without doing any type of sorting on the questions array, the document would always return like above which is the natural ascending order of the data entered.

What is strange is that the generated IDs are in reversed order as you can see:

key 0 => 5e2088563824e72ea5ee70c3
key 1 => 5e2088563824e72ea5ee70be
key 2 => 5e2088563824e72ea5ee70b9
key 3 => 5e2088563824e72ea5ee70b4
key 4 => 5e2088563824e72ea5ee70af

What is the expected behavior?

I expected the generated ID to match with the key of the array (ascending) so, it should be like:

key 0 => 5e2088563824e72ea5ee7096
key 1 => 5e2088563824e72ea5ee709b
key 2 => 5e2088563824e72ea5ee70a0
key 3 => 5e2088563824e72ea5ee70a5
key 4 => 5e2088563824e72ea5ee70aa

Why does Mongoose give the first element in the array the highest ObjectID and the last element the lowest ObjectID?

However, behaviour of the generated document IDs is normal like the auto-increment of MySQL (ascending). It's just the nested arrays that have the reversed order.

Is this a bug or is it the normal behavior? Why is it designed like this if this is normal?

confirmed-bug

Most helpful comment

I see, so I may create a new issue. Thanks for the feedback. This is useful to enrich the behavior of the issue

All 3 comments

I have a similar issue: Some times when I make document.children.push(newElement) the push operation inserts newElement at the top of the array instead at the bottom (as vanilla array.prototype.push works). This is not happening every time, but I haven't found a pattern yet. Why is behaving this way?

This is actually a different issue. For me, the order of data entered is always respected. The problem is the _id is reversed (first data get latest _id and vice versa) and it's like this everytime and even for deeply nested arrays.

I see, so I may create a new issue. Thanks for the feedback. This is useful to enrich the behavior of the issue

Was this page helpful?
0 / 5 - 0 ratings