In a web application, I have a set of objects in a database with a numeric field responsible for organizing them. On the client side, these objects appear as a sortable list, allowing users to change their order.
At the moment, I have two solutions for managing order updates, and none of them satisfy me.
The first one is simple: every time the user changes the order of the elements, the updated list is moved, it receives all the identifiers of the elements in the array, sends them to the server and releases a series of updates, where each order of the elements is the ID index in the array.
The disadvantages of this approach: a lot of unnecessary updates, the inability to properly handle the situation when the array of objects sent to the server does not contain all entity identifiers.
The second of them is as follows: when the user changes the order of the positions, the changed identifier of the element is sent to the server along with the identifier of the elements that "surround" the changed element, it has a new place in the list. On the server, the new order is calculated using (previous.order + next.order) / 2. Therefore, if an element with order 3 moves between points with orders 5 and 6, the new order becomes 5.5.
This solution requires only one update for each change, but also has a serious problem: because of the algorithm used, each change increases the decimal part in serial numbers, and sooner or later it requires more accuracy than my database can provide (I use MongoDB for this case, but I Believe it is not so important).
My question is, are there any other more effective and correct ways, or maybe my current approaches can be improved somehow?
After testing all the suggestions, I came up with a solution based on the advice of Tom Anderson. The final algorithm is as follows:1. When the user changes location, then moves the identifier of the element, and his new old neighborhood identifier is sent to the server (I decided to use the identifier instead of ordinals to ensure security and the reason for concurrency).2. On the server, the movement of the ordinal element becomes prev_neighbour.ordinal + 1, and all other ordinals that are higher than or equal to the moved new order also increase by 1.( ) , , , , (, ID ) .