Search code examples
node.jsmongodbhandlebars.jsexpress-handlebars

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.


Solution

  • 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.