繁体   English   中英

将数组与 Javascript 中的字符串匹配(NodeJS + EJS)

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

已编辑

控制器中的功能:

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 });

进入 show.ejs 页面:

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

这将返回以下内容(来自 mongoDB):

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

现在 <% post.author %> 将返回帖子作者的 id,如 5d68ef0e3e133417dcc60c64

事情是,在 ejs 模板中,我想将 post.author 与 user._id 匹配,如果它们匹配,我希望它返回匹配的特定用户的 user.username。 我希望现在更清楚了。 再次感谢

您可以使用find() : find() 方法返回数组中满足提供的测试函数的第一个元素的值。 否则返回 undefined。

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

这将返回_id属性与post.author值匹配的post.author

在这里工作小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM