【问题标题】:Matching array to a string in Javascript (NodeJS + EJS)将数组与Javascript中的字符串匹配(NodeJS + EJS)
【发布时间】:2020-01-03 15:40:54
【问题描述】:

已编辑

控制器中的功能:

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 } ]

现在 将返回帖子作者的 ID,如 5d68ef0e3e133417dcc60c64

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

【问题讨论】:

  • 1.不,日志不是数组。循环的每次迭代只打印一个字符串。 2. 请发布您的数据(帖子和用户的原始数组),以便我们为您提供一些代码。
  • 我已经相应地编辑了帖子。

标签: javascript node.js mongodb foreach ejs


【解决方案1】:

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

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

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

工作小提琴here

【讨论】:

  • 我认为应该是return user._id == post.author._id,假设作者是名字。或return user == post.author 但我不确定它是否适用于 JS
  • @noname 问题说:console.log(post.author) 将返回一个字符串,如果它不在 forEach 循环“bye1”中,所以似乎作者属性是那个字符串
  • 对不起,它没有帮助,因为我试图通过 EJS 模板在前端访问它,而 users.find afaik 将不起作用。 p.s 我已经编辑了更多细节的帖子
  • 你不能在渲染之前做它并传递给前端吗?
  • @BrettGregson 是的,但在我的理解中,作者的意思是“一个字符串”而不是“id”的字符串,而且因为他提到他使用 mongodb,所以我可以假设作者想将 user._idpost.author._id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 2015-06-10
  • 1970-01-01
  • 2021-04-28
  • 2012-04-26
相关资源
最近更新 更多