Or05230
Or05230

Reputation: 83

Matching array to a string in Javascript (NodeJS + EJS)

edited

Function in the controller:

async postShow(req, res, next) {
        let post = await Post.findById(req.params.id).populate({
            path: 'reviews',
            options: { sort: { '_id': -1 } },
            populate: {
                path: 'author',
                model: 'User'
            }
        });
        let users = await User.find().exec();

        res.render('posts/show', { post, users });

going into the show.ejs page:

 <% users.forEach(function(user) { %>
                        <% console.log(user) %>
                    <% }) %>

this will return the following (from mongoDB) :

  { image: { secure_url: '/images/default-profile.jpg' },
    _id: 5d68ea449ee71014067986e2,
    username: 'john',
    email: '[email protected]',
    __v: 0 },
  { image: { secure_url: '/images/default-profile.jpg' },
    _id: 5d68ef0e3e133417dcc60c64,
    username: 'Tom',
    email: '[email protected]',
    __v: 0 } ]

Now <% post.author %> will return the post author's id like 5d68ef0e3e133417dcc60c64

Thing is, In the ejs template i want to match post.author to user._id and if they match i want it to return user.username of the specific user that was matched. I hope it's a bit more clear now. Thanks again

Upvotes: 1

Views: 466

Answers (1)

Brett Gregson
Brett Gregson

Reputation: 5913

You can use find(): The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

var found = users.find(function(user) {
  return user._id == post.author;
});

This will return the user who's _id property matches the post.author value

Working fiddle here

Upvotes: 1

Related Questions