Wednesday 17 May 2017

Model method defined in mongoose does not work with handlebars

I have defined a method for a model using mongoose. I am able to utilize these methods in a javascript file just fine however when calling the methods from a handlebars file, to which I have passed a mongoose model, it does not work as expected.

Upon further examination, the behavior changes depending on the this keyword. Consider the following method that simple concatenates two string fields for a model:

jobSchema.methods.location = function() {
  let location = this.city + ", " + this.state;
  return location;
};

I have a handlebars partial where I pass a model as such


  <div class="col-md-6">
    <div class="job-tile mb-4">
      <h5 class="job-tile-title"></h5>
      <div class="job-tile-loc text-muted"></div>
    </div>
  </div>


This partial renders the correct output and the method location is called with the right context and this references the given model.

However, I have another handlebars template where I pass in a model attempt to call the same method.

<h2></h2>
<h3></h3>

With this template, I get an undefined output and when I print this from within the method. The latter template gives me the whole context for the handlebars file whereas the former gives me just the model.



via user3500333

No comments:

Post a Comment