user557657
user557657

Reputation: 896

Not able to compare Object Id using handlebars?

This is my first time using Handlebars. I am trying to compare user _id with logged in user id. I am saving data in MongoDB using mongoose. I found a helper from StackOverflow but it doesn't seem to compare value. The schema for user and Tracker and code I am using is below.

var trackerSchema = new mongoose.Schema({
    description: {
        type: String,
        required: [true, 'Please add an description']
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    }
});
mongoose.model('Tracker', trackerSchema);

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }

});
const User = mongoose.model('User', UserSchema);

Helper function in app.js file

const hbs = exphb.create({
    extname: 'hbs',
    defaultLayout: 'mainLayout',
    layoutDir: __dirname + 'views/layouts/',
    partialsDir: __dirname + '/views/partials/',

    helpers: {
        ifEqual: function (v1, v2, options) {
            if (v1 != v2) {
                return options.inverse(this);
            }
            return options.fn(this);
        },
    }
})

Using helper function ifEqual in handlebar file

{{#each list}}
<td>{{this.createdAt}}</td>
<td>{{this.user}}</td> //i am seeing this.user for example - **5ef9fb54f4bb8dff810104f7**    
<td>
    {{#ifEqual this.user looged_user_id }} //looged_user_id coming from req.user._id.toString()
    <a href="/tracker/{{this._id}}"> Edit </a>
    <a href="/tracker/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"> Delete
    </a>
    {{else}}
    <a href="#"> Edit </a>
    <a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
    </a>
    {{/ifEqual}}
</td>
</tr>
{{/each}}

Please guide how can I compare two _ids.

Upvotes: 1

Views: 860

Answers (2)

Ravi Kukreja
Ravi Kukreja

Reputation: 647

You were missing two things:

  1. Sending looged_user_id to your hbs:

    res.render("tracker/list", { list: body, logged_user_id: req.user._id, });

  2. Accessing logged_user_id it the right way inside the #each handlebar loop. When inside the loop you cannot directly use the data passed. You have to provide the right path to logged_user_id which in your case would be ../logged_user_id.

The ../ path segment references the parent template scope using which you can access logged_user_id.

Upvotes: 1

BINFAS K
BINFAS K

Reputation: 255

In your code you need to pass your looged_user_id to template first, then only it will get in your helper function.

try this on http://tryhandlebarsjs.com/

Template:

    {{#each list}}
    <td>{{this.createdAt}}</td>
    <td>{{this.user}}</td> 
    <td>
        {{#ifCond this.user}} //Here 1 is just hardcoded insted of that need to change with actal variable
        <a href="/tracker/{{this._id}}"> Edit for if </a>
        <a href="/tracker/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"> Delete looged_user_id
        </a>
        {{else}}
        <a href="#"> Edit for else </a>
        <a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
        </a>
        {{/ifCond}}
    </td>
    </tr>
    {{/each}}

Context:

    {
        "list": [{
            "user": 1,
            "content": "hello"
        },{
            "user": 2,
            "content": "world"
        }],
    }

Register Helper function:

    Handlebars.registerHelper('ifCond', function(v1, options) {
      if(v1 === looged_user_id ) {
        return options.fn(this);
      }
      return options.inverse(this);
    });

Result:

    <td></td>
    <td>1</td> 
    <td>
        <a href="/tracker/"> Edit for if </a>
        <a href="/tracker/delete/" onclick="return confirm('Are you sure to delete this record ?');"> Delete looged_user_id
        </a>
    </td>
    </tr>
    <td></td>
    <td>2</td> 
    <td>
        <a href="#"> Edit for else </a>
        <a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
        </a>
    </td>
    </tr>

Upvotes: 0

Related Questions