【问题标题】:Displaying result from MongoDB collection with Pug使用 Pug 显示 MongoDB 集合的结果
【发布时间】:2020-05-21 01:39:44
【问题描述】:

我有一个 MongoDB 集合,它的结构是这样的;

{
    "_id": "4rc4f9653fc4ff04dd7d31h6",
    "title": "my title",
    "url": "https://myurl.com",
    "author": "john",
    "created": {
        "$date": "2020-05-20T04:12:47.457Z"
    },
    "vote": 1619
}

我有以下pug 布局;

block content
  h1 #{title}
  ul.list-group
    each entry, i in entries
      li.list-group-item
        a(href=entry.url, target='new')= entry.title
        |, 
        span.text-success=entry.author
        |, 
        span.text-success=entry.vote

这工作正常,结果是这样的;

mytitle,约翰,1619

我也想添加日期字段。所以我最后的结果应该是这样的;

mytitle, 约翰, 1619, 2020-05-20

我尝试添加created 字段,如下所示,但这并没有为创建带来任何价值。知道我在这里缺少什么吗?

a(href=entry.url, target='new')= entry.title
|, 
span.text-success=entry.author
|, 
span.text-success=entry.vote
|, 
span.text-success=entry.created

【问题讨论】:

    标签: node.js mongodb mongodb-query pug


    【解决方案1】:

    在您的数据中,created 是一个对象,而不是日期字符串。要访问日期字符串,您需要执行以下操作:

    span.text-success= entry.created['$date']
    

    【讨论】:

    • 这给了我错误:“无法读取未定义的属性 '$date'”
    • 您是在each 循环中调用它吗?
    • 这是我的 app.js 顺便说一句:Entry.aggregate([{ $group: { _id: "$url", author: { $first: "$author" }, vote: { $max: "$vote" }, url: { $first: "$url" }, title: { $first: "$title" } } },{ $sort:{ vote:-1} },{ $limit : 500 }]).exec(function(err, entries).. 我想知道我是否需要在此处包含日期..
    • 是的,否则它不会被传递给 Pug。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2017-06-18
    • 1970-01-01
    • 2021-05-25
    • 2017-04-19
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多