Use Meteor to retrieve the value from the initial collection in order to locate the value in the second collection

Currently, I have two sets of data:

  1. Users, containing userId, firstname, and surname.
  2. Answers, containing answerId, questionId, and user.

In the 'Answers' collection, the 'user' field corresponds to the userId of the user who provided the answer.

While I am able to retrieve the userId from the answers collection, my goal now is to utilize this userId to access the Firstname and Surname from the Users collection.

An alternative approach could be to avoid inserting the userId into the Answers collection altogether and instead use the firstname and surname fields. However, I am unsure how to implement this method as well.

I hope my query is clear and that someone can provide assistance!

Sincerely, L

Answer №1

Each answer document in the Answers collection can be looped through using the forEach() method to find the corresponding user document in the Users collection based on the ID, illustrated below:

Answers = new Meteor.Collection("answers");
Users = new Meteor.Collection("users");

if(Meteor.isClient) {
    processed_data = []; 

    Deps.autorun(function (c) {
        console.log('run');
        var cursor = Answers.find({}, { sort: { time: 1 }});
        if (!cursor.count()) return;

        cursor.forEach(function (ans) {
            var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
            ans.user = user;
            processed_data.push(ans);
        }); 

        console.log(processed_data);
        c.stop();
    }); 
}

The data will stay reactive as Deps.autorun ensures that the block inside function() {...} is re-executed whenever there's any change in a reactive variable or document, like updates, removals, inserts, or other reactive changes.

To update the userId in the Answers collection with the actual user document containing firstname and surname, you can leverage the Bulk API operations for efficient updates. Access the raw collection and database objects via rawCollection() and rawDatabase() methods on Mongo.Collection.

Answers = new Meteor.Collection("answers");
Users = new Meteor.Collection("users");

if (Meteor.isClient) {
    Template.answerlist.helpers({
        answers: function () {
            processed_data = []; 

            Deps.autorun(function (c) {
                console.log('run');
                var cursor = Answers.find({}, { sort: { time: 1 }});
                if (!cursor.count()) return;

                cursor.forEach(function (ans) {
                    var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
                    ans.user = user;
                    processed_data.push(ans);
                }); 

                console.log(processed_data);
                c.stop();
            }); 

            return processed_data;
        }
    });

    Template.answerlist.events({
        'click #updateAnswers': function(ev) {
            Meteor.call('updateAnswersUser');
        }
    });

}


if (Meteor.isServer) {
    Meteor.startup(function () {
        Meteor.methods({
            updateAnswersUser: function() {
                var bulkOp = Answers.rawCollection().initializeUnorderedBulkOp(),
                    counter = 0;
                Answers.find({}).forEach(function(ans) {
                    var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
                    var changes = {};
                    changes["user"] = user;
                    bulkOp.find({"_id": ans._id}).updateOne({ "$set": changes });

                    counter++;
                    if (counter % 1000 == 0) {
                        // Execute per 1000 operations and re-initialize every 1000 update statements
                        bulkOp.execute(function(e, r) {
                            console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
                        });
                        bulkOp = Answers.rawCollection().initializeUnorderedBulkOp();
                    }
                }); 

                // Clean up queues
                if (counter % 1000 != 0){
                    bulkOp.execute(function(e, r) {
                        console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
                    });
                }
            }
        }); 
    });
}

Answer №2

To retrieve the Firstname and surname fields from the Users collection, you can use the following query:

Users.find({_id: userId}, {fields:{Firstname: 1, surname: 1}}).fetch();

The value of userId should correspond to the user's id in the Answers collection.

It is assumed that this value matches with _id in the Users collection.

Storing the user's Firstname and surname in each answer would lead to unnecessary duplication of data.

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

The "Go" button on iPhone triggers an error before the page is sent back

I am facing an issue with a web page that has a form containing multiple submit buttons with different functionalities like clearing the form, performing a calculation, or adding another entry line. The problem arises only on iPhone devices (tested on bot ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Adjust the viewport width based on the width of the device

Having difficulty adjusting the meta tag viewport content width based on device width, I am struggling to achieve my desired outcome. Here is the code snippet I have been working with: Code snippet: <meta id="viewport" name="viewport" content="width=d ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Tips for selecting the correct date on a DatePicker using selenium?

I am facing an issue with my selenium test related to a date picker on a webpage. The task is to select a specific date (e.g., 14/2/2012) by clicking on the correct day. However, the date picker is generated using jQuery as shown in the code snippet belo ...

Implementing pagination in a node.js application using pg-promise and fetching data from

Upon reviewing the documentation at https://github.com/vitaly-t/pg-promise/wiki/Data-Imports, I found a comprehensive guide on importing data using pg-promise. Although the example provided works for the showcased scenario, I am unsure how to adapt it to ...

Cross-origin resource sharing policy is preventing a request from the client-side to the server

I am currently working on a Vue.js application and I am facing an issue with CORS policy blocking my backend requests. I am using axios to make the request to the backend for data that I need to display charts on the UI. Here is the code snippet of my char ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

What is the best way to extract text directly from a span element without including the text of its child nodes?

I am dealing with a piece of HTML that is dynamically generated, and it looks like this: <span> 10/10/2012 <div class="calendar"> lots of text elements here </div> </span> Is there a way to specifically retrieve the tex ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

Dual Networked Socket.IO Connection

I have set up a node.js server with an angular.js frontent and I am facing a problem with Socket.IO connections. The issue arises when double Socket.IO connections open, causing my page to hang. var self = this; self.app = express(); self.http = http.Ser ...

Building a Dynamic Web Widget with the Perfect Blend of HTML, JS,

While developing a javascript-based web widget, I am aiming to steer clear of using iframes and avoid relying on the page's CSS. It is infeasible for me to utilize custom CSS, as it defeats the purpose, and iframe integration would not present a user- ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

The output is generated by React useContext with a delay

When using the data obtained from useContext to verify if the logged-in user is an Admin, there seems to be a delay where it initially returns "undefined" and then after about 5 seconds, it provides the actual value. This causes the code to break since it ...

The collection is not an array

I am currently running the following code: var n = []; jQuery.toJSON( n ); Interestingly, on one page I receive "[]", while on another I get ""[]"". Both pages are utilizing the same version of jQuery along with a toJson Plugin. Upon inspecting the arra ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...

Reduce the size of log messages in cypress

I am looking to shorten the cypress messages to a more concise string, for instance: Cypress log Transform to: -assert expected #buy-price-field to have value 17,169.00. Is there a way to achieve this? I have searched through the documentation but hav ...