Updating multiple documents with different values
<p>I'm using jquery ui's sortable function (<a href="https://jqueryui.com/sortable/" rel="noreferrer">source</a>) to re-arrange elements. I've built custom callbacks to create an list of those elements. So when i move an element, all elements is given a new position id. It could look like this:</p>

<pre><code>[{
    id_of_element_in_database: 12,
    new_position: 0
}, {
    id_of_element_in_database: 16,
    new_position: 1
}, {
    id_of_element_in_database: 14,
    new_position: 2
}]
</code></pre>

<p>I'm sending this list to my back-end by doing a simple <strong>Ajax post</strong></p>

<pre><code>$.post('/position', { data: list });
</code></pre>

<p><strong>Route</strong></p>

<pre><code>router.post('/position', (req, res) =&gt; {
    console.log(req.body.data); // This prints the array of objects above.
});
</code></pre>

<p><strong>Schema</strong></p>

<pre><code>mongoose.Schema({
    id: Number,
    position: Number,
    ...
});
</code></pre>

<p>Now I can't figure out how to change the position of all documents effectively. Creating a crappy loop of the array and doing multiple database-requests can't be the best approach.</p>

<p>I've tried that here and this feels so wrong.</p>

<pre><code>for (let i in req.body.data) {
    collection.update({ id: req.body.data[i].id }, { position: req.body.data[i].position });
</code></pre>

<p>There must be something else i can do to achieve this. I've tried google without any luck.</p>