Apply a specific class to the data retrieved from MongoDB in a Meteor application depending on a field value in the database

In my Mongo collection documents, I have an array containing various objects for a chat app. When I try to display the data, I encounter an issue where all messages are getting the "my-message" class instead of just my messages.

I'm struggling to target only my messages with the my-message class. How do I fix this?

Document Structure:

{
  _id: "RCe9ZBS9PfkwrqKvg"
  borrowerId: "Rg33iLJyRYqHyMpk4"
  messages: Array[{text:messageBody, from:currentUserId, date:New Date()}]
  ownerId: "fPv5yWJiSqFX3bAhR"
  reqId: "KXErmpFJ7LiCbKsqc"
}

Template:

  {{#with getMessages}}
    {{#each messages}}
        <p class="{{#if myMessages}} my-message {{/if}}">{{text}}</p>
    {{/each}}
  {{/with}}

Helper:

Template.reqMessages.helpers({
  getMessages: function () {
    var theReqId = FlowRouter.getParam("reqId");
    return Messages.findOne({reqId: theReqId});
  },
  myMessages: function () {
    var currentUserId = Meteor.userId();
    var theReqId = FlowRouter.getParam("reqId");
    return Messages.find({reqId: theReqId, 
      messages: [{$elemMatch: {
        from: currentUserId
      }}]});
  }
});

Answer №1

To achieve the desired outcome, it appears that the following code snippet should be utilized:

{{#with getMessages}}
  {{#each messages}}
    <p class="{{#if isMine}}my-message{{/if}}">{{text}}</p>
  {{/each}}
{{/with}}

Template.reqMessages.helpers({
  getMessages: function () {
    var theReqId = FlowRouter.getParam("reqId");
    return Messages.findOne({reqId: theReqId});
  },
  isMine: function () {
    return this.from === Meteor.userId();
  }
});

By iterating through the messages array within your template, the context (this) of the helper function refers to each object in the array. To determine if the message is from the user, a comparison between this.from and Meteor.userId() can be made.

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

Updating new objects in Angular using JavaScript Object-Oriented Programming may not be working

Recently delving into OOP in JavaScript while working on an AngularJS website, I encountered a situation where my object methods were only altering the properties within the class, but not affecting the new object itself. //Class Var Item = function() { ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

Storing PDF files in MongoDB with GoLang and mgo

After exploring various sources on saving files using mgo, I'm still struggling to find a solution for my specific requirement. Can anyone help me out? This code inserts an object into MongoDb: var dbSchoolPojo dbSchool i := bson.NewObjectId() dbSch ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

Is history.pushState capable of more than just making an xhr request?

I've hit a roadblock in my current project. The issue I'm facing is getting a registration page to load. The XHR request is returning the output of the PHP code, which is causing problems. My goal is to have it load as a document rather than an ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

It is important for the button size to remain consistent, regardless of any increase in text content

My goal was to keep the button size fixed, even as the text on it grows. This is the current code I am using: .button { border: none; color: white; padding: 10px 50px; text-align: center; text-decoration: none; display: inline-block; font ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Tips and tricks for effectively utilizing Material UI's sx props in conjunction with a styles object

In my current project, I am working with a styles object that is structured as follows: styles = { color: "#333", fontSize: "16px", }; When applying these styles to a Material UI component like the example below, everything works a ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

JavaScript issue: TypeError - Information.map is not a function. Learn how to properly use .map method

Currently, I am learning how to use CRUD in React with Express and Node. I have successfully inserted data into the database, but I encountered an error when trying to represent the data using .map. You can see the issue with <Input onClick="{getCR ...

The pause and restart buttons are malfunctioning and are not functional

My goal is to create a stopwatch using JavaScript that can start and stop the timer. I want to store the time data in my MySQL database when the user presses the stop button. However, I am facing issues with the pause buttons not functioning properly. f ...

Creating an effective Google Login Button in a React application

Struggling to implement a Login/Sign In Google Button on my page using react, I'm new to this framework and it's just not working as expected. Following tutorials from the internet but still facing issues. To summarize, I'm utilizing tailw ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Is there a way to eliminate the 'All Files' option from an HTML file input field?

I have implemented a feature to allow users to upload custom files using . Currently, I am restricting the allowed file types to only ".Txt, .SVG, .BMP, .JPEG" by using accept=".Txt,.SVG,.BMP,.JPEG". This setting causes the browser's file-select dial ...

Can you explain the significance of npm WARN excluding symbolic link?

Could you please explain the meaning of npm WARN excluding symbolic link? Also, any advice on how to resolve this issue? ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...