繁体   English   中英

没有使用Array.Map()更新Javascript对象

[英]Javascript object not updating with Array.Map()

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

如您所见,我正在尝试使用Array.Map添加一个time属性,该属性将此字符串作为值添加到posts对象。

这似乎有效,因为在控制台中记录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对象的独特之处?

先谢谢您的帮助。

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

暂无
暂无

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

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