简体   繁体   中英

Add class to data received from Mongo based on a field value in Mongo, on a Meteor app

I got mongo collection documents which includes an array which includes bunch of other objects. This is for a simple chat app.

I access all the data within the document and display it. Nonetheless, I have difficulties to give my-message class to my messages. When I write this below code, it gives all messages my-message class. :/

So what am I doing wrong?

Object 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
      }}]});
  }
});

I think you mean to do this:

{{#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();
  }
});

Since you are already looping through the messages array in your template, the helper's context (this) is each object in the array. You can determine if it is from the user by simply comparing this.from and Meteor.userId() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM