Can any one advise me why I am not getting the _id as first feild after save or update?

Once I save a new document I expect to get the _id as first element, how can I get sort this as per my requirement? (Using Mongoose ODM)
Please advise. Thank you!

            "commenterName": "James Mustic",
            "user": "63499ae5cbba271c29375a25",
            "note": "Called the payer for follow up",
            "_id": "634cb6d055cff6bd70a19c44",
            "updatedAt": "2022-10-17T01:58:40.509Z",
            "createdAt": "2022-10-17T01:58:40.509Z"

Hi @Faslu_Rahman_K ,

If this is a newly created JavaScript object, I expect the order of fields will be the same as creation order unless a field name is numeric (since JavaScript has special sorting logic for object property keys). When this object is written to the MongoDB server, the _id field will be moved first during the write operation (per The _id Field documentation) but that field order change will not be reflected in your application until you refetch the document.

The order of fields in JavaScript objects is generally not guaranteed unless you are using an ordered field like an array or a data structure like a Map that preserves order. Can you provide more detail on why you require a specific field ordering?

Also, please also share more details on your environment:

  • Mongoose
  • MongoDB Node.js driver
  • MongoDB server
  • steps to reproduce this issue


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.