I have an express app where you can make and view posts. I am trying to make it so an edit icon appears next to the users post if they made it. I've tried to do this with an handlebar helper.
editIcon: function (user, loggedUser, floating = true) {
console.log(user, loggedUser);
if (user._id.toString() == loggedUser._id.toString()) {
if (floating) {
return `<div>edit icon</div>`;
}
} else {
return '';
}
},
Basically user is the user._id. loggedUser is the id inside the post and it's the same as the user id.
This is what my handlebar looks like:
{{#each posts}}
<div class="post-extra">
<div class="card-image">
<!-- User is the logged in user and then post id (_id) -->
{{{editIcon user _id}}}
</div>
<a href="#" class="user-link">{{user.username}}</a>
<h2>{{postTitle}}</h2>
</div>
{{else}}
<p>No posts to display</p>
{{/each}}
</div>
The problem is that when I console log user and loggedUser, the id's returned are different. In my mongodb though, the user id and the user id inside the post are the same.
My post and user objects:
Post:
_id:ObjectId("5f8523d8b58f4919908e3895") <-- this is being returned..
postTitle:"Test post"
postBody:"<div>stuff</div>"
user:ObjectId("5f8522c9c0ec222ea4b7c8c0") <-- instead of this
createdAt:2020-10-13T03:49:44.333+00:00
__v:0
User:
_id: ObjectId("5f8522c9c0ec222ea4b7c8c0"), // User id
username: 'test',
email: '[email protected]',
password: 'hashed password here',
createdAt: 2020-10-13T03:45:13.018Z,
__v: 0
As you are calling your
editIcon
helper as{{{editIcon user _id}}}
, you are passing theuser
of thepost
and the_id
of thepost
. This is incorrect because what you want to compare is theuser
of the post to theuser
of the request (the logged-inuser
).From the example you have provided it is not clear whether you have access to the
user
of the request in your template. If you do, it certainly won't be nested in apost
object, so you will need a path to step up a context or two to access it. The result would look something like:In this example, the logged-in
user
is a sibling of theposts
Array, but your data structure may be different.I have created a fiddle for your reference.