Syncing fields between collections in Meteor's MongoDB

I have a document for a scheduled meeting that looks like this:

{
    "name": "Meeting Name",
    "uuid": "NYoc2aL6",
    "participants": [
        {
            "id": "JLKGZnfFkGvX9DHgz",
            "status": "joined",
            "name": "Guest 03"
        },
        {
            // newly invited user, user hasn't logged in with invite url yet
            "id": "",
            "status": "invited",
            "name": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d3dbd7dfdaf6d3dbd7dfda98d5d9db">[email protected]</a>"
        }
    ]
}

Now, I want to synchronize the 'name' field with the corresponding name in the Users collection. Is there any automated process at the database level to achieve this, or will I have to manually update it in each location where the name is changed?

Answer №1

In the world of Meteor development, there’s a pattern that tends to crop up frequently. By leveraging the matb33:collection-hooks package, you can effectively "hook" into collection updates and keep shared values synchronized. This process should ideally take place on the server-side to avoid any issues with accessing related documents.

Here's an example to illustrate this concept:

Meteor.users.after.update((userId, doc, fieldNames, modifier, options)=>{
  if ( fieldNames.indexOf('profile.name') > -1 ){ // the name was changed
    Meetings.update({ 'participants.id': doc._id },
      { $set: { 'participants.name': doc.profile.name }},
      { multi: true });
  }
});

Answer №2

As far as I'm aware, there isn't a built-in method to achieve this in Mongo or Meteor automatically. However, one possible approach could be extracting common fields from your document and linking them with an ID instead. This practice is referred to as "Database Normalization," where redundant data is removed from tables (or collections in Mongo) to avoid issues like the one you're facing.

Answer №3

One way to automate this process is by continuously monitoring the users database for any changes:

let usersObserver = Meteor.users.find();
usersObserver.observeChanges({"changed":function(id, fields){
    if(fields.profile.name){
        // Perform the necessary actions here
    }
}});

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

Attempting to erase a Raphael document with no content entered

After some trial and error, I have successfully created a progress bar using user input in a form. However, I am facing an issue where I want the paper to clear when the input field is blank by using paper.clear();. Currently, it leaves one status bar (a b ...

What is the best way to enable 'taggable' content in MongoDb?

How can I fulfill the following criteria in MongoDB: Content of records can include text, images, multiple fields, and are typically unstructured documents Records can be labeled with keywords or key phrases Retrieval of records is done by searching usin ...

How to retrieve JSON data from unidentified objects using JQuery

I have made an AJAX call and received a JSON file as the response: [ { "LINKNAME": "Annual Training", "HITS": 1 }, { "LINKNAME": "In Focus Newsletter", "HITS": 1 }, { "LINKNAME": "NITA (secured)" ...

Implementing dynamic routing to manage the path /a/b-c-d-:e-:f

Here is a sample route: server.get("/something/best-shoes-in-india-:brand-:location", (req, res) => { res.send(JSON.stringify(req.params)) }) For example, if brand name = adidas and location = Delhi: If the URL is => "/something/best-shoes-in- ...

The terminal does not recognize the nodemon command

My goal is to automate server reloads using nodemon. I have successfully installed it locally and set the start command as nodemon app.js with this code: "scripts": { "start": "nodemon app.js" } Initially, everything was running smoothly. However, ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

The mysterious case of the missing currentUserObj in Angular with rxjs Subject

I've encountered an issue while trying to pass data from my login component to the user-profile component using an rxjs subject. Despite calling the sendUser method in the login component and subscribing to the observable in the user-profile component ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

The client-side HTML is unable to connect to the API due to a timed-out error

I am experiencing an issue with my API not receiving data from client-side code to the /api endpoint that I have set up on the localhost of the webserver on port 3000. How can I ensure that the server-side code properly processes the post request and conso ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

What is the method for deactivating the voting button for a product review when the review's ID is present in local storage?

Managing reviews with user voting in a React app can be challenging. Each review can be deemed helpful or not, and each product may have multiple reviews. When a user votes on a review, the corresponding button should be disabled. I store the clicked revie ...

Tips for implementing HTML5 history push state rather than using window.location.hash in your web application

I am currently using window.location.hash for managing history. How can I update this to use HTML5 history push state instead? var stateHistory = []; function changeHistory(page) { var l = stateHistory.length, ...

Leverage AngularJS $http.get method to continuously fetch JSON array upon scrolling

Here is a snippet of code that utilizes AngularJS to retrieve a JSON response. I am looking for assistance in implementing a functionality where the page should make additional requests when the user scrolls to the bottom, continuing until the JSON array ...

What is the best way to handle an array of string inputs in Apollo Server using GQL?

My current typeDefs file contains a custom Books type structured like this: type: Books { bookId: String authors: [String] description: String title: String } For storing data, I am utilizing MongoDB with the following model schema: const book ...

When it comes to JavaScript, it considers the number 0 as equivalent

I am facing an issue with my spring endpoint that is returning an Enum named StatoPagamentoEnum: Java enum definition @JsonFormat(shape = JsonFormat.Shape.ARRAY) public enum StatoPagamentoEnum { DA_PAGARE(0), PARZIALMENTE_PAGATA(1), PAGATA(2 ...

Promise.withResolvers is throwing an error in pdf.js version 4.4.168

While using pdf.js 4.4.168 to display PDF files in the browser, I encountered an error when trying to open the site in Safari 16.4: Unexpected Application Error! Promise.withResolvers is not a function. (In 'Promise.withResolvers()', 'Promis ...

Angular failing to bind data within an image element

I am currently following an Angular series on Lynda.com and facing a roadblock. Although I am new to Angular, the main issue is that I am attempting to iterate through data in order to fetch images from a folder and assign an h1 name to each image. Below i ...

Issue with jQuery Uploadify within an Update Panel

I am facing an issue with jQuery Uploadify where the FileUpload control is not re-rendering after the UpdatePanel gets updated. Below is the JavaScript code in use: $(document).ready( function () { $("#").uploadify({ ...

The use of multiple $match steps in MongoDB aggregation can lead to sluggish query performance

After encountering the issue discussed in Query with $in and $nin doesn't use index, I attempted to utilize aggregation for setting the sequence of operations. db.assets.aggregate([ { "$match": { "tags": { "$in": ["blah"] } ...

How come the pop-up isn't displaying in the middle of the screen?

I have encountered a positioning issue while using a semantic modal with Angular. The problem arises when I try to display the modal as it does not appear in the correct position. https://i.sstatic.net/o033E.png Below is the code snippet from my HTML fil ...