Searching Meteor Collections by the IDs obtained from a different collection

I am currently managing 2 collections.

ItemList = new Mongo.Collection('items');
BorrowerDetails = new Mongo.Collection('borrow');

ItemList.insert({
    brand: "brand-Name",
    type: "brand-Type",
    ._id: id
});

BorrowerDetails.insert({
    key: "ItemList.id", //equals to .id of the ItemList Collection
    name : "borrowerName"
});

Here's my question:
I want to know how I can retrieve records from the BorrowerDetails Collection based on a specific type from the ItemList Collection.

For example, fetching all records from the BorrowerDetails Collection where the key is equal to the id of a record in the ItemList Collection with a type of "Desktop".

return BorrowerDetails.find(
    { key : 
        ItemList.find(
            { type : 'Desktop' },
            { fields: {'_id':1 } }
        )
    }
); //error!  

Answer №1

Please note that currently nodejs is not installed on my laptop, therefore there may be errors in the following code as I am unable to test it.

Firstly, create a publication file (e.g. server\publications\borrowPub.js). Within this file, you will need to define a publication method. The concept here is straightforward - retrieve the itemid array first and then use it as a parameter in Mongo select $in.

Meteor.publish('queryBorrowerTypeDesktop', function(criteria)
{

   var itemArr = ItemList.find( { type : 'Desktop' },
                             { fields: {'_id':1 } });
   if(itemArr){
    //itemArr found, so do a select in using the array of item  id we retrieved earlier
    var borrowers = BorrowerDetails.find({ key: { $in: itemArr } });
    return borrowers;
   }else{
     //found nothing- so return nothing
     return [] 
   }
});

Secondly, in the router:

Router.route('/test', {
  name: 'test',
 action: function()
 {
   //change accordingly.
 },
 waitOn: function()
 {//subscribe from publisher that we just created...
  return [
    Meteor.subscribe('queryBorrowerTypeDesktop') 
  ];
 },
 data: function() {
 if(Meteor.userId())
 {
     // also include the sorting and limit so your page will not crash. change accordingly. 
     return {
       borrowerDetails: BorrowerDetails.find({},{sort: {name: -1},        limit: 30}),
  }
  }
 }
});

Keep in mind that in the data section, BorrowerDetails.find() does not require filtering because it has already been filtered during the subscribe process and cached in MiniMongo within your browser.

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

Parameters for both index and value must be included when passing a function to the .attr() method

Here is a code snippet: <div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div> <script> $( "div" ) .attr( "id", function( ind ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

The production server is unable to successfully complete the npm run build command

After successfully building a nextjs 14.1.4 project on my local Windows machine using npm run build, I encountered an error when trying to build it on my production server: Ubuntu 22.04.3 LTS with the same command. ./src/pages/about.tsx:7:20 Type error: Ca ...

Node-inspector actively searching for the specified <module>.js upon execution of the 'require' function

Just starting out with Node Inspector on Linux Mint 14. I encountered an issue while trying to debug a simple .js file that contains console.log("Hello World"). Here's what happened: node-debug app.js Node Inspector launched properly, paused at the ...

Utilizing jQuery to submit the form

After clicking the search icon, it displays an alert with the message ok, but not h. Based on the code snippet below, it is intended to display alerts for both ok and h. <?php if(isset($_POST['search'])){ echo "<script type='text/ ...

What is the best way to replace a double quotation mark within a string that is already enclosed in double quotation marks using JavaScript

How can I handle a double quote (") within double quotes while using a regular expression in the JSON string provided below? [{ "LDAP_ID":"a", "LAC_NO":"1153274", "ACTION":"VBE", "DATE_OF_ACTION":"06-01-2006 AM 12:00:00", "RESPONS ...

Simply input the data into the fields of the weekly tds

I am facing an issue with my code where, upon clicking the "apply to all" button, it automatically populates the columns for Monday through Friday only. However, I need Saturday and Sunday to remain empty without any data. $('#elemento').click ...

Tips on destructuring an object property from a Pinia getter that may return an object based on a condition

I obtained this particular Store: export const useMyStore = defineStore('myStore', { state: () => { return { openTransOnly: false, keyword: '', openTransStatus: { nextPage: 0, complete: false }, pastDueT ...

Customized Grafana dashboard with scripted elements

I'm running into an issue while using grafana with graphite data. When I attempt to parse the data, I encounter an error due to the server not providing a JSON response. I am experimenting with scripted dashboards and utilizing the script found here: ...

Is it feasible in Angular2 to add CSS to a component using a service?

I have a component named A containing 5 images. Out of the 5, only one image is in color and clickable, while the remaining 4 are greyed out using the CSS class below: .not_opened{ -webkit-filter: grayscale(85%); } The greyscale images are not clickabl ...

Prevent duplicate entries in a JavaScript key-value data structure

Seeking advice from a novice. I am working on a project where I need to create a list with a Key/Value structure. I have assigned the Id as the Key and the rest of the information as the value, so as I add more records, they get appended to my list $scope ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

What is the best way to merge and nest connected JSON elements?

I am working with two separate JSON files that I need to merge into one single JSON object for use on the frontend of my project. fragments.json [ { "id": 2, "title": "John Smith is nice", "reports& ...

You are currently logged in as 'not specified'

Currently, I am sorting through the various tokens I have for my Discord bots and trying to easily identify which token belongs to which bot. Previously, when logging in with `client.login()`, everything was smooth sailing. However, now when I attempt to u ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...

Measuring the pixel distance of scrolling on a page with overflow hidden

I am trying to implement a functionality where a class is toggled for the body element on a page with hidden overflow and single screen, based on the amount of scroll. However, there is a challenge: the scrolling behavior involves animation rather than act ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...