Reputation: 2852
I want to change order of objects in slides sub document with respect to the sort_order key in it.
For Eg: I want to move slide with title A3 above A2. ie. sort_order
value of A3 (3) is changed to 2 and that of A2 will be changed to 3, and viceversa in case of moving down.
How to do ??
Below is the db object.
{
"_id" : ObjectId("5a3b8cc68884dd1140a9a5b8"),
"title" : "Sort Test",
"user_id" : ObjectId("59e08e45f081170f582e95cc"),
"status" : "active",
"slides" : [
{
"_id" : ObjectId("5a3b8cc68884dd1140a9a5b9"),
"sort_order" : 0,
"content" : "Sort Test",
"title" : "Sort Test"
},
{
"_id" : ObjectId("5a3b8cda8884dd1140a9a5ba"),
"sort_order" : 1,
"content" : "Text Contents here...",
"title" : "A1"
},
{
"_id" : ObjectId("5a3b8ce48884dd1140a9a5bb"),
"sort_order" : 2,
"content" : "Text Contents here...",
"title" : "A2"
},
{
"_id" : ObjectId("5a3b8cec8884dd1140a9a5bc"),
"sort_order" : 3,
"content" : "Text Contents here...",
"title" : "A3"
},
{
"_id" : ObjectId("5a3b8cec8884dd1140455bc"),
"sort_order" : 4,
"content" : "Text Contents here...",
"title" : "A4"
}
],
"description" : "Sort Test",
"__v" : 0
}
Upvotes: 1
Views: 74
Reputation: 3111
With this method you can create a new array with same elements and the ones you ask for, switched (I think is what you asked). Then you just have to update slides field in the DB with new array.
var dbObject = {
"_id" : ObjectId("5a3b8cc68884dd1140a9a5b8"),
"title" : "Sort Test",
"user_id" : ObjectId("59e08e45f081170f582e95cc"),
"status" : "active",
"slides" : [
{
"_id" : ObjectId("5a3b8cc68884dd1140a9a5b9"),
"sort_order" : 0,
"content" : "Sort Test",
"title" : "Sort Test"
},
{
"_id" : ObjectId("5a3b8cda8884dd1140a9a5ba"),
"sort_order" : 1,
"content" : "Text Contents here...",
"title" : "A1"
},
{
"_id" : ObjectId("5a3b8ce48884dd1140a9a5bb"),
"sort_order" : 2,
"content" : "Text Contents here...",
"title" : "A2"
},
{
"_id" : ObjectId("5a3b8cec8884dd1140a9a5bc"),
"sort_order" : 3,
"content" : "Text Contents here...",
"title" : "A3"
},
{
"_id" : ObjectId("5a3b8cec8884dd1140455bc"),
"sort_order" : 4,
"content" : "Text Contents here...",
"title" : "A4"
}
],
"description" : "Sort Test",
"__v" : 0
}
var slides = dbObject.slides;
var switchElementsInArray = function(array, sortOrder1, sortOrder2) {
var newArray = [];
for(var element of array) {
if(element.sort_order === sortOrder1) {
newArray.push(elem2);
} else if(element.sort_order === sortOrder2) {
newArray.push(elem1);
} else {
newArray.push(element);
}
}
return newArray;
}
var newSlides = switchElementsInArray(slides, 2, 3);
Upvotes: 1