Is it possible to organize a cursor based on IDs from a separate document array?

When updating the SpaceBars @index native helper after sorting items in an #each iteration, I believe the correct approach is to sort the cursor used within the #each.

The cursor is derived from an Items collection. The array used for sorting belongs to a different collection document (Projects) containing an ordered list of each published item ID.

After moving an item to a new position, I update each item index within the project document array using the sortable stop function. This involves removing it first with $pull, then inserting it back at a specific position with $push.

stop: function(e, ui) {
  var project = Projects.findOne();
  // obtain dragged element and its adjacent elements

  el = ui.item.get(0)
  before = ui.item.prev().get(0)
  after = ui.item.next().get(0)

  console.log(Blaze.getData(el)._id); // retrieve dropped item's ID

  if(!before) {
    console.log(after.dataset.index); // get index of next element

    Projects.update({_id: project._id},
      {$pull:
        {
          items: Blaze.getData(el)._id
        }
      })
      Projects.update({_id: project._id},
        {$push:
          {
            items:
            {
              $each:[Blaze.getData(el)._id],
              $position:0
            }
          }
        })
      } else if(!after) {
        Projects.update({_id: project._id},
          {$pull:
            {
              items: Blaze.getData(el)._id
            }
          })
          Projects.update({_id: project._id},
            {$push:
              {
                items: Blaze.getData(el)._id
              }
            })
          }  else
          Projects.update({_id: project._id},
            {$pull:
              {
                items: Blaze.getData(el)._id
              }
            })
            Projects.update({_id: project._id},
              {$push:
                {
                  items:
                  {
                    $each:[Blaze.getData(el)._id],
                    $position:after.dataset.index -1
                  }
                }
              })
            }

As you can see, the above function uses the index property of the item (e.g., $position:after.dataset.index -1). This is what needs to be updated by sorting the cursor.

In summary, there is an ordered array of IDs:

items : {
   Id2131,
   Id4233,
   Id2243,
   Id2331,
   Id2455,
   Id2123
}

Additionally, there is a publication with matching IDs but not in the correct order.

To align the cursor Items.find() with the order of the other document array, how can the sorting be done?

Answer №1

After some experimentation, a breakthrough finally occurred to me. Let me share the steps I took:

In order to optimize my #each iteration function, I modified it to return a sorted array version of the results obtained from Items.find(). Therefore, instead of just returning Items.find(), it now returns sortItems(Items.find())

The implementation of the sortItems function is as follows:

var sortItems = function(cursor) {
  if(!cursor) {
    return [];
  }
  var rawData = cursor.fetch();

  var projectData = Projects.findOne();
  var sortedArray = [];
  
  _.each(projectData.items, function(itemId) {
    _.each(rawData, function(item) {
      if (item._id === itemId) {
        sortedArray.push(item);
      }
    });
  });

  return sortedArray;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

Tips for sending an array of input field values through an Ajax request

In my current web form, there is a dynamic option that adds rows with the same attributes. These rows need to be submitted through an Ajax call to my PHP for insertion into the database. Access: <tr> <td><input type"text" name="access[nam ...

The transparency in Three.js took a turn for the worse after the update from r67 to r68

I encountered a strange problem when switching from three.js version 67 to version 68. In version 67, everything appeared correctly (triangles behind transparent triangles were visible), but in version 68, something seems to have gone awry. Below are two ...

Encountered an issue with launching Chrome in Puppeteer for Node.js

My code was uploaded to EC2 AWS, but unfortunately it is not working properly after the upload. Interestingly, it runs correctly on localhost. Despite trying various solutions, I am still facing this issue. Any suggestions on the correct approach to resolv ...

Leveraging Python to authenticate on a website using JavaScript and secure HTTPS connection

I am looking to utilize python for logging into a website that utilizes javascript and https encryption. The specific site I'm referring to is: My goal is to create a python script that successfully logs in, with the intention of later translating th ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

Javascript auto submission fails to execute following the completion of the printer script

As someone new to javascript, I have a question. I have a function called sendToQuickPrinter() that prints correctly, but after it finishes executing, I need to automatically submit a form to return to my "cart.php" page. I feel like I'm almost there, ...

Steps for deleting an item from an array based on its property

Seeking advice on how to remove an entire object from an array that contains a specific value. The current array includes multiple objects, as shown below: var cars= [ {key: 'browser', label: 'Chrome'}, {key: 'browser', labe ...

Transform a JavaScript Array into a JSON entity

Currently working on a Mail Merge project using Google Apps Script, I've encountered an issue with displaying inline images in the email body. After sending the email using GmailApp.sendEmail(), all inline images are shown as attachments instead of be ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

What is the process for rendering components in a simulated DOM environment using enzyme?

I am working with a components library and have an interesting challenge. I have created a Tooltip component that renders a tooltip div at the very bottom of the document's body. Now, I want to test whether this div element appears after hovering over ...

A command-line style text input box in HTML

I am currently developing a unique text box that enables the execution of custom commands using a customized syntax. This concept is intended to help teach programming to children. For example, when a user types a $ sign, the program responds with an aler ...

Vue.JS: The central layout element and navigation system

I have a primary layout component (consists of a fixed top header and a left side menu with multiple links created using the router-link component) as well as a "dynamic" layout component that serves as the heart of the page. My goal is to change the cen ...

What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really a ...

send information via an ajax call to trigger a callback function

Can data be passed through an Ajax request to the Callback function without using global variables? For example, can the request function pass the passData through the callback function while also getting normal response data? function makeRequest(callba ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...