Saving the ordering of items in db

I’m working on a project using mongodb and react. Very stumped on this. Any help is much appreciated.

Scenario:

  • database: a master list of objects (keys- name, category, orderNum)
  • frontend: items from master list are displayed either on ListA or ListB (depending on each item’s category:value)
  • user can create/delete/move item from list to list. User can also move item’s position to any spot on a list. These actions save the orderNum value of items and the current ordering of items persists when the user refreshes screen

Do I have to update the orderNum of each object in the master list (db) every time the user creates/update/change the position of an item? This doesnt sound right.

Saving the “orderNum” is a property of the user, so this information should be saved in relation to the user. Since we are using mongoDb, you could put this information in its own schema, or nested within the user’s schema. Since you mentioned 2 lists (listA, and listB) you probably will need to save 2 different lists for different orders, but otherwise the setup is the same for both.

Regardless of where you save the order, the data you save should look like an array of item ids. When the user moves an item you could either save the entire “new order” or you send a request to your server with the “move” and it updates the order.

On the client-side, React will need to get the list of user’s “orders”, which is just an array of Ids still, and “show” the orders for the user in the given order.


The key part of this is identifying that the ordering is related to the user, so if another user is using the system, they will see the same items, but in their own order they set.

You describe your DB in a SQL way and that’s what you would do with it. With Mongo, that’s not a case. If number of lists is defined (2) and you won’t have exceptionally large lists, then just store things same way you’d do in JS:

user: {
  listA: [{...}, {...}, {...}],
  listB: [{...}, {...}, {...}]
}

Mongo will keep the order and you don’t need the category. Slightly slower writes, but hugely faster reads - that’s the way you go. Any attempt to control order of the list manually is bad idea.