【问题标题】:Javascript object not updating with Array.Map()Javascript 对象未使用 Array.Map() 更新
【发布时间】:2019-08-26 13:08:19
【问题描述】:

我有一个 Express API,其中我有以下 Mongoose 查询,它从数据库中提取帖子,然后我想将数据库中的时间戳(一个 Date() 对象)转换为相对时间字符串。

如您所见,我正在尝试使用 Array.Map 将具有此字符串作为值的 time 属性添加到帖子对象。

这似乎可行,因为在控制台中记录 items[0].time 会返回正确的值(请参阅 cose 中的注释)。

但是!使用 res.json 发回对象时,time 属性不在其中。

我认为这可能是客户端缓存问题,但是当在 res.json 中添加另一个值时,新值与帖子一起发送就好了。

Post.find({}, 'author text timestamp')
        .sort({ _id: -1 })
        .populate({ path: 'author', select: 'username' })
        .exec(function(error, posts) {
          if (error) {
            console.error(error)
          }


          items = posts.map(function(item) {
            item.time = moment(item.timestamp).fromNow()
            return item
          })

          console.log('Relative date:' + items[0].time) // This logs: "Relative date:an hour ago"

          res.json({
            posts: items
          })
          /*
            Response:

            posts: {
              0: {
                author: {_id: "5c98f40f793edf61bcc94b4d", username: "Admin"},
                text: "Why",
                timestamp: "2019-04-04T15:46:36.142Z",
                _id: "5ca626dc45734a2612acbcd2"
              }
            }
          */
        })

这是与服务器相关的缓存问题还是我不​​知道的 Mongoose 对象独有的问题?

提前感谢您的帮助。

【问题讨论】:

  • 您正在处理不可变的猫鼬Document objects。您可以在架构中的转换中添加time 或使用item.toObject()map() 中转换为pojo
  • @charlietfl 非常感谢!您的回复激发了我寻找更清洁的解决方案,我会在一秒钟内发布它;)!

标签: javascript arrays json express mongoose


【解决方案1】:

我能够在我的代码中使用 Post.find().lean() 解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-31
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多