使用 EJS 显示对象的 属性 时出现问题

Problem displaying property of an object, using EJS

我正在尝试在我的应用程序的评论中插入作者的用户名,在 ejs 模板中。

以下标签:

<%= review.author %>

按预期工作,输出:

{ _id: 5eff6793e7f26811e848ceb1, username: 'mike', __v: 0 }

但是添加用户名 属性,即这个标签:

<%= review.author.username %>

这是来自相应控制器的代码:

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'
    }
  });
  res.render('posts/show', { post });
},

输出虚无。我是新手,但我不知道为什么我会在这个看似简单的问题上陷入困境。我哪里出错了?

谢谢!

使用 lean() 来 return 对象而不是 mongoose 文档

let post = await Post.findById(req.params.id).lean().populate({
    path: 'reviews',
    options: { sort: { '_id': -1 } },
    populate: {
      path: 'author',
      model: 'User'
    }
  });
  res.render('posts/show', { post });
},

<%= review.author.username %>

以上内容无效,因为 author 的内容(Schema.Types.ObjectId,引用了 User 模型)包含在多余的 array 中的一个对象中:

const ReviewSchema = new Schema({
  body: String,
  rating: Number,
  author: [{
      type: Schema.Types.ObjectId,
      ref: 'User'
    }]
});

删除阵列解决了这个问题。我不确定为什么最初包含它。更正:

const ReviewSchema = new Schema({
  body: String,
  rating: Number,
  author: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    }
});