Exploring the relationship between two collections in Meteor, specifically using MongoDB for querying by value

Currently, I am developing a social media platform similar to Twitter but have encountered an issue with sorting.

Below are the collections I am working with:

Tweets:
  createdAt: Date
  body:      String
  userId:    String

Events:
  createdAt: Date
  type:      String (either 'retweet' or 'like')
  tweetId:   String
  userId:    String

Whenever a user retweets a Tweet, a new Event document is generated to keep track of the tweet and user IDs.

When visiting a user's profile page, I search for all Tweets written by the user or that have been retweeted by the user. To ensure all necessary tweets are available, a reactive join is performed on the server so the Tweets collection contains all relevant information.

The challenge lies in sorting: currently, all Tweets are sorted based on their createdAt value. This results in retweeted tweets from previous days appearing below the user's recent tweets.

In essence, I need a method to sort Tweets either by their own createdAt field or by the createdAt field of an associated Event if one exists.


I am open to restructuring my models if there is a more efficient approach. One idea was to create a new Tweet each time a retweet occurs, but this poses issues with maintaining accurate counts for likeCount and retweetCount. If every retweet generates a new Tweet and subsequent likes or retweets occur, it would lead to incorrect numbers or require excessive denormalization updates.

Answer №1

  1. Ensure that an event is created for every tweet posted
  2. Utilize the [reywood:publish-composite]) package to publish the sorted Events collection based on the Event.createdAt key and restrict it to the desired number of events to display.
  3. In your template, use {{#each events}} instead of {{each tweets}}
  4. Create a template helper to retrieve the tweet's body content

Template Helper:

Template.myTemplate.helpers({
  events: function(){
    return Events.find({},{sort: {createdAt: -1}});
  },
  body: function(){
    return Tweets.findOne({ _id: this.tweetId }).body;
  }
});

Following this approach aligns with normalization. Given the tweet's brevity, optimizing performance can involve directly copying the body field from each tweet into the corresponding Events document.

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

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

Link multiple collections in Mongoose by populating an array of referenced documents from an embedded collection within another collection

const schemaA = new mongoose.Schema({ Cs: [{type: mongoose.Schema.Types.ObjectId, ref: "ModelC"}] }); const ModelA = mongoose.model("ModelA", schemaA); const schemaB = new mongoose.Schema({ Cs: [schemaC] }); const ModelB = mongoose.model("ModelB ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Retrieve information and display it in a text field using ajax

Hi there, I'm having some trouble with my current code and would appreciate any help you can offer. My goal is to filter data in a search box and display the corresponding results in text boxes. I've been searching online for hours trying to find ...

showing information from a table column

Utilizing the jQuery DataTables plugin with a JSF <h:dataTable>. The page contains 86 records. +++++++++++++++++++++++++++++++++++++ + SN. + Name + Email + +++++++++++++++++++++++++++++++++++++ + 1 + Name 1 + Email 1 + + ...

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

Trigger the select dropdown when a key is clicked

I am currently working on a project in react where I am utilizing the Select component from material. When I open the dropdown and press a key on my keyboard, the option starting with that key gets automatically selected. This behavior is also observed in ...

Page experiencing issues with JavaScript functionality

Here is a simple function that I am using to shake a form when the user's email is not valid: function shakeForm() { var l = 10; for( var i = 0; i < 10; i++ ) $("form").animate( { 'margin-left': "+=" + ( l = -l ) + 'px ...

Effective ways to engage with a window that is supervised by a different controller?

Although the question may appear vague initially, I struggled to find a better way to convey my idea. Let me elaborate on it in detail. In my SPA application, I have MasterController connected to the <html> tag. This MasterController consists of all ...

Ways to initiate a change event once all multiselect choices have been finalized

I am struggling with a multiselect dropdown element that contains check boxes in my application. The issue I am facing is that the change function associated with this element gets triggered every time a check box is clicked. I would like the change functi ...

Is it possible to display items based on their specific category?

I am currently working on creating an ecommerce store using express and mongodb. One of the challenges I am facing is implementing categories for the shop. Specifically, I want to only display items that correspond to a selected category when a customer cl ...

How can I retrieve the latest 30 records from a MongoDB collection without starting from the beginning?

When I use the .sort({_id:1}).limit(30) method, the results only display messages from 0 to 30. I want to see messages from 40 to 70 (for example) instead. This means I am seeing all messages up to 30, but not any newer ones. How can I retrieve exactly 3 ...

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

Updating with `mongoose.findOneAndUpdate()` alters the existing data stored within my Node.js application

I came across another person seeking advice on a value override, but unfortunately it remains unanswered. Hopefully, someone can point out the mistake I might be making! Here's the situation... var vote = req.body.vote; var boolVote; (vote === &apos ...

Using Node/Express, we can implement an API that includes email verification through JWT tokens. Additionally,

I'm encountering a peculiar issue while developing a NodeJS/Express API that utilizes JSON web tokens for email verification. Below are the code snippets for both the user registration and email confirmation routes. Strangely, when I test these routes ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

What is the best way to organize objects based on their keys?

Looking to iterate through object values and append text if the key matches in JavaScript. The object is as follows: { "id": "n27", "name": "Thomas More", "className": "level-1", & ...

What is the process of setting up various initialization parameters for a DataTable?

Here is a snippet of JavaScript code I have been using to initialize a DataTable: $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', &a ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...